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

    1001 数组中和等于K的数对

    基准时间限制:秒 空间限制:131072 KB 

    给出一个整数K和一个无序数组AA的元素为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 NNA数组的长度。(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

    import java.util.Arrays;
    import java.util.Scanner;
    public class Main1 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner sc=new Scanner(System.in);
            while(sc.hasNext()){
                
                int k=sc.nextInt();
                int n=sc.nextInt();
                int a[]=new int[n+1];
                for(int i=0;i<n;i++)a[i]=sc.nextInt();
                Arrays.sort(a,0,n);
                int j=n-1;
                boolean flag=false;
                for(int i=0;i<n-1;i++)
                {
                    while(i<j && a[i]+a[j]>k) j--;
                    if(a[i]+a[j]==k && i<j)
                    {
                        flag=true;
                        System.out.println(a[i]+" "+a[j]);
                    }
                }
                if(!flag)System.out.println("No Solution");
            }
                   sc.close();
        }
    
    }
  • 相关阅读:
    (转)五大常用算法之二:动态规划算法
    (转)五大常用算法之一:分治算法
    dict
    usaco2
    usaco3
    usaco4
    usaco1
    并查集
    洛谷P1428小鱼比可爱
    洛谷P1967货车运输
  • 原文地址:https://www.cnblogs.com/watchfree/p/5350723.html
Copyright © 2011-2022 走看看