博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第2章 数字之魅——快速寻找满足条件的两个数
阅读量:4641 次
发布时间:2019-06-09

本文共 2462 字,大约阅读时间需要 8 分钟。

快速寻找满足条件的两个数

问题描述

  能否快速找出一个数组中的两个数字,让这两个数字之和等于一个给定的数字,为了简化起见,我们假设这个数组中肯定存在这样一组或以上符合要求的解。

分析与解法

【解法一】

代码如下:

1 package chapter2shuzizhimei.findtwonumber; 2 /** 3  * 快速寻找满足条件的两个数 4  * 【解法一】 5  * @author DELL 6  * 7  */ 8 public class FindTowNumber1 { 9     //定义一个二元组类10     public static class Tuple{11         public double a;12         public double b;13         public Tuple(double a, double b){14             this.a = a;15             this.b = b;16         }17     }18     //寻找满足条件的两个数19     public static Tuple find(double a[],double sum){20         int n = a.length;21         for(int i=0;i

程序运行结果如下:

数组中和为:10.0的两个数为:9.0 1.0

【解法二】

完整代码如下:

 

1 package chapter2shuzizhimei.findtwonumber; 2 /** 3  * 快速寻找满足条件的两个数 4  * 【解法二】 5  * @author DELL 6  * 7  */ 8 public class FindTowNumber2 { 9     //定义一个二元组类10     public static class Tuple{11         public double a;12         public double b;13         public Tuple(double a, double b){14             this.a = a;15             this.b = b;16         }17     }18     19     //快速排序的一次划分20     public static int partition(double a[], int first, int last) {21         double temp = a[first];22         int i = first, j = last;23         while (i < j) {24             while (i < j && a[j] >= temp) {25                 j--;26             }27             if (i < j)28                 a[i] = a[j];29             while (i < j && a[i] <= temp) {30                 i++;31             }32             if (i < j)33                 a[j] = a[i];34         }35         a[i] = temp;36         return i;37     }38 39     // 快速排序40     public static void quickSort(double a[], int first, int last) {41         if (first >= last)42             return;43         int i = partition(a, first, last);44         quickSort(a, first, i - 1);45         quickSort(a, i + 1, last);46     }47     48     //寻找满足条件的两个数49     public static Tuple find(double a[],double sum){50         int n = a.length;51         quickSort(a,0,n-1);  //从小到大排序52         int i,j;53         for(i=0,j=n-1;i
sum){58 j--;59 }else{60 i++;61 }62 }63 return null;64 }65 public static void main(String[] args) {66 double a[] = {3,8,4,9,12,5,1};67 double sum = 9;68 Tuple t = find(a,sum);69 System.out.println("数组中和为:"+sum+"的两个数为:"+t.a+" "+t.b);70 71 }72 73 }

程序运行结果如下:

数组中和为:9.0的两个数为:1.0 8.0

 

转载于:https://www.cnblogs.com/gaopeng527/p/4626140.html

你可能感兴趣的文章
⑥python模块初识、pyc和PyCodeObject
查看>>
object-c中管理文件和目录:NSFileManager使用方法
查看>>
Kibana:分析及可视化日志文件
查看>>
nodejs pm2使用
查看>>
cocos2d-x 3.10 PageView BUG
查看>>
装饰器的基本使用:用户登录
查看>>
CSS选择器总结
查看>>
mysql中sql语句
查看>>
head/tail实现
查看>>
sql语句的各种模糊查询语句
查看>>
vlc 学习网
查看>>
Python20-Day05
查看>>
Real World Haskell 第七章 I/O
查看>>
C#操作OFFICE一(EXCEL)
查看>>
【js操作url参数】获取指定url参数值、取指定url参数并转为json对象
查看>>
ABAP 程序间的调用
查看>>
移动端单屏解决方案
查看>>
web渗透测试基本步骤
查看>>
使用Struts2标签遍历集合
查看>>
angular.isUndefined()
查看>>