4 条题解
-
0
#include<bits/stdc++.h> using namespace std; typedef long long ll; int n; int a[100010]; int x; int main() { ios::sync_with_stdio(false); cin.tie(0); cin>>n>>x; for(int i=0;i<n;i++) cin>>a[i]; int cnt=0; int l=0,r=n-1; int sum; while(l<r){ sum = a[l]+a[r]; if(sum==x){ cnt++; l++; } else if(sum>x){ r--; } else{ l++; } } cout<<cnt; return 0; }` -
0
Python题解
import sys input = lambda:sys.stdin.readline().strip() ans=0 n,x = map(int,input().split()) a = [0] + list(map(int,input().split())) i, j = 1, n while(i<j): if a[i] + a[j] == x: ans+=1 i+=1 continue if a[i] + a[j] < x: i+=1 continue if a[i] + a[j] > x: j-=1 continue print(ans) -
0
c++题解
#include<bits/stdc++.h> using namespace std; #define int long long int a[100100],x,n,ans=0; signed main(){ cin>>n>>x; for(int i=1;i<=n;i++){ cin>>a[i]; } int l=1,r=n; while(l<r){ if(a[l]+a[r]==x){ ans++; r--; l++; } else if(a[l]+a[r]>x){ r--;//如果大于x就减少右边 } else l++;//否则增加左边 } cout<<ans; } -
0
JAVA AC代码(map映射完成两数之和):
import java.util.*; import java.util.StringTokenizer; import java.io.*; public class Main { public static void main(String[] args) { Map<Integer,Integer> map=new HashMap<>(); int n=in.nextInt(); int x=in.nextInt(); int ans=0; for(int i=1;i<=n;i++){ int number=in.nextInt(); map.put(number,1); if(map.containsKey(x-number)&&number!=x-number) ans++; } out.println(ans); out.close(); } static FastReader in=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static class FastReader{ static BufferedReader br; static StringTokenizer st; FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next() { String str=""; while(st==null||!st.hasMoreElements()) { try { str=br.readLine(); }catch(IOException e) { throw new RuntimeException(e); } st=new StringTokenizer(str); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
- 1
信息
- ID
- 54
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 普及−
- 标签
- 递交数
- 380
- 已通过
- 147
- 上传者