zoukankan      html  css  js  c++  java
  • 1001 数组中和等于K的数对

    基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

    给出一个整数K和一个无序数组A,A的元素为N个互不相同的整数,找出数组A中所有和等于K的数对。例如K = 8,数组A:{-1,6,5,3,4,2,9,0,8},所有和等于8的数对包括(-1,9),(0,8),(2,6),(3,5)。
     
    Input
    第1行:用空格隔开的2个数,K N,N为A数组的长度。(2 <= N <= 50000,-10^9 <= K <= 10^9)
    第2 - N + 1行:A数组的N个元素。(-10^9 <= A[i] <= 10^9) 
    Output
    第1 - M行:每行2个数,要求较小的数在前面,并且这M个数对按照较小的数升序排列。
    如果不存在任何一组解则输出:No Solution。
    Input示例
    8 9
    -1
    6
    5
    3
    4
    2
    9
    0
    8
    Output示例
    -1 9
    0 8
    2 6
    3 5

    今晚唯一一道没有一发A的题目,因为i跟t的变化问题也是调了许久。

    附AC代码:

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstring>
     4 using namespace std;
     5 
     6 const int INF=1<<30;
     7 
     8 int a[50010];
     9 
    10 int main(){
    11     int n;long long k;
    12     cin>>k>>n;
    13     for(int i=0;i<n;i++){
    14         cin>>a[i];
    15     }
    16     sort(a,a+n);
    17     /*for(int i=0;i<n;i++)
    18     cout<<a[i]<<" ";*/
    19     int t=n-1,i=0,ans=0;
    20     while(1){
    21         if(a[i]+a[t]==k&&i<t){
    22             cout<<a[i]<<" "<<a[t]<<endl;
    23             ans++;
    24             i++;
    25         }
    26         else if(a[i]+a[t]>k){
    27             t--;
    28         }
    29         else if(a[i]+a[t]<k){
    30             i++;
    31         }
    32         if(i>=t)
    33         break;
    34     }
    35     if(ans==0){
    36         cout<<"No Solution"<<endl;
    37     }
    38     return 0;
    39 }

    附全场最佳:

     1 #include <stdio.h>
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 const int N = 50005;
     6 
     7 int k, n;
     8 int a[N];
     9 
    10 int main() {
    11   int i, j;
    12   scanf("%d %d", &k, &n);
    13   for (i = 0; i < n; i++) {
    14     scanf("%d", &a[i]);
    15   }
    16   sort(a, a + n);
    17   bool flag = false;
    18   i = 0; j = n - 1;
    19   while (i < j) {
    20     n = a[i] + a[j];
    21     if (n == k) { printf("%d %d
    ", a[i++], a[j--]); flag = true; }
    22     else if (n < k) { i++; }
    23     else { j--; }
    24   }
    25   if (!flag) { puts("No Solution"); }
    26 }
  • 相关阅读:
    js小案例---1.随机10不重复10数并排序2.一次输入10数并输出和
    23种设计模式-----转载
    类与类之间的关系-----转载
    设计模式六大原则-----转载
    配置JDK时环境变量path和JAVA_HOME的作用是什么?
    安装和配置JDK,并给出安装、配置JDK的步骤。
    1.Java为什么能跨平台运行?请简述原理。
    求圆的周长和面积
    java第一节课
    相关元素操作
  • 原文地址:https://www.cnblogs.com/Kiven5197/p/5778045.html
Copyright © 2011-2022 走看看