1001数组中和等于k的数对
2016-07-23 20:30
387 查看
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 ; 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 ; 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\n",stu[i].x,stu[i].y); } return 0; }
相关文章推荐
- webstorm笔记
- 星际之门(一)(cayley定理n阶完全图的生成数个数,快速幂)
- KMP算法 HDU 1686 Oulipo 也就是乌力波啦~~
- 图像文件读入和显示
- 什么是一个对象?
- (贪心) Vacations 求休息的最少天数
- 对象的引用
- 网络修复-可以上qq但是网页等打不开
- NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorld
- 迭代加深搜索
- 双系统ubuntu16.04 64位安装android studio并启动虚拟机
- LeetCode[367] Valid Perfect Square
- while(cin>>temp)如何结束循环
- 欧氏距离比较相似度的python实现
- codeforces #364d As Fast As Possible
- 走遍欧洲 —— 伊比利亚半岛
- BGP选路之local-preference
- 配置中的master指的是master 的候选节点
- mybatis自学入门实例(一)
- 【VS开发】【图像处理】RGB Bayer Color分析