1001数组中和等于k的数对
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
这个是原题,我用c++写了一遍,总是超时,我觉得我的思路太常规,于是上网找到一些优化程序的方法,先给出java通过的代码,思路就是先输入这些数,可采用while语句来实现循环输入,
import java.util.Arrays; import java.util.Scanner; public class Arr { public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int k=sc.nextInt();//输入k和n int n=sc.nextInt(); int [] arr=new int [n]; for(int i=0;i<arr.length;i++){//输入这一串数字 arr[i]=sc.nextInt(); } Arrays.sort(arr);//给数组进行排序吧 int j=n-1; boolean is=false; for(int i=0;i<n;i++){ while(i<j&&arr[i]+arr[j]>k){//利用二分查找快速合适的数对 j--; } if(arr[i]+arr[j]==k&&i<j){//判断数对是否合适 is=true; System.out.println(arr[i]+" "+arr[j]); } } if(is==false){ System.out.println("No Solution"); } } sc.close(); } }
下来c++代码思路差不多唯一不同的是没有使用二分,使用遍历数组,看代码,超时代码
<pre name="code" class="cpp">#include<stdio.h> #include<algorithm> using namespace std; struct node{ int x; int y; }stu[50000]; bool cmp(const node &c,const node &b){ return b.x>c.x; } int main(){ int k,n; scanf("%d%d",&k,&n); int arr[n]; for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } int t=0; for(int i=0;i<n-1;i++){ for(int j=i+1;j<n-1;j++) { if(arr[i]+arr[j]==k){ t++; if(arr[i]<arr[j]){ stu[t-1].x=arr[i]; stu[t-1].y=arr[j]; } else{ stu[t-1].x=arr[j]; stu[t-1].y=arr[i]; } } } } sort(arr,arr+t,cmp); for(int i=0;i<t;i++){ printf("%d %d ",stu[i].x,stu[i].y); } return 0; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 51nod1001 数组中和等于K的数对
- 下一篇: 数组中和等于K的数对