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 }
  • 相关阅读:
    [oracle] linux Oracle 安装配置
    [dns] linux dns 安装配置
    [apache] linux Apache 编译安装
    [yum] linux yum 配置本地和ftp源
    [ftp] linux ftp 安装配置
    [ssh 无密码访问]linux ssh公匙密匙无密码访问
    [php ] linux php 搭建
    [mysql ] linux mysal 修改字符集
    [ mysql ] linux mysql 忘记root密码重置
    国安是冠军
  • 原文地址:https://www.cnblogs.com/Kiven5197/p/5778045.html
Copyright © 2011-2022 走看看