第2章 数字之魅——快速寻找满足条件的两个数
2015-07-07 10:46
429 查看
快速寻找满足条件的两个数
问题描述
能否快速找出一个数组中的两个数字,让这两个数字之和等于一个给定的数字,为了简化起见,我们假设这个数组中肯定存在这样一组或以上符合要求的解。分析与解法
【解法一】
![](http://images0.cnblogs.com/blog2015/689103/201507/070959255335995.png)
代码如下:
package chapter2shuzizhimei.findtwonumber; /** * 快速寻找满足条件的两个数 * 【解法一】 * @author DELL * */ public class FindTowNumber1 { //定义一个二元组类 public static class Tuple{ public double a; public double b; public Tuple(double a, double b){ this.a = a; this.b = b; } } //寻找满足条件的两个数 public static Tuple find(double a[],double sum){ int n = a.length; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i]+a[j]==sum){ Tuple t = new Tuple(a[i],a[j]); return t; } } } return null; } public static void main(String[] args) { double a[] = {3,8,4,9,12,5,1}; double sum = 10; Tuple t = find(a,sum); System.out.println("数组中和为:"+sum+"的两个数为:"+t.a+" "+t.b); } }
程序运行结果如下:
数组中和为:10.0的两个数为:9.0 1.0
【解法二】
![](http://images0.cnblogs.com/blog2015/689103/201507/071000431742610.png)
![](http://images0.cnblogs.com/blog2015/689103/201507/071003057991804.png)
完整代码如下:
package chapter2shuzizhimei.findtwonumber; /** * 快速寻找满足条件的两个数 * 【解法二】 * @author DELL * */ public class FindTowNumber2 { //定义一个二元组类 public static class Tuple{ public double a; public double b; public Tuple(double a, double b){ this.a = a; this.b = b; } } //快速排序的一次划分 public static int partition(double a[], int first, int last) { double temp = a[first]; int i = first, j = last; while (i < j) { while (i < j && a[j] >= temp) { j--; } if (i < j) a[i] = a[j]; while (i < j && a[i] <= temp) { i++; } if (i < j) a[j] = a[i]; } a[i] = temp; return i; } // 快速排序 public static void quickSort(double a[], int first, int last) { if (first >= last) return; int i = partition(a, first, last); quickSort(a, first, i - 1); quickSort(a, i + 1, last); } //寻找满足条件的两个数 public static Tuple find(double a[],double sum){ int n = a.length; quickSort(a,0,n-1); //从小到大排序 int i,j; for(i=0,j=n-1;i<j;){ if(a[i]+a[j]==sum){ Tuple t = new Tuple(a[i],a[j]); return t; }else if(a[i]+a[j]>sum){ j--; }else{ i++; } } return null; } public static void main(String[] args) { double a[] = {3,8,4,9,12,5,1}; double sum = 9; Tuple t = find(a,sum); System.out.println("数组中和为:"+sum+"的两个数为:"+t.a+" "+t.b); } }
程序运行结果如下:
数组中和为:9.0的两个数为:1.0 8.0
相关文章推荐
- Creating Shazam in Java
- tomcat+nginx+redis集群试验
- 从头到尾彻底理解KMP
- 设置行间距,自动适应高度
- 斐波那契数列问题的解
- Loadrunner中web脚本转成JavaVuser脚本
- Size Classes with Xcode 6
- 如何测试你自己的 RubyGem?
- 整合SSH步骤,版本:Strust2.3+Spring3.2+Hibernate3.6
- 学习jquery easyui 的一个中文网站
- Oracle数据库启动命令dbstart没有反应
- CentOS Apache编译安装及APR not found错误排除
- opencv cvThreshold() cvAdaptiveThreshold()
- @ResponseBody
- OpenCV的HOG+SVM训练程序注意事项
- JavaScript中的数据真假判断
- Java break [flag]; 与continue [flag]; 区别
- Html5+Css3拾遗
- C/C++回调函数
- Apple移动设备处理器指令集 armv6、armv7、armv7s及arm64