第2章 数字之魅——快速寻找满足条件的两个数
生活随笔
收集整理的這篇文章主要介紹了
第2章 数字之魅——快速寻找满足条件的两个数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
快速尋找滿足條件的兩個數
問題描述
能否快速找出一個數組中的兩個數字,讓這兩個數字之和等于一個給定的數字,為了簡化起見,我們假設這個數組中肯定存在這樣一組或以上符合要求的解。
分析與解法
【解法一】
代碼如下:
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<n;i++){ 22 for(int j=i+1;j<n;j++){ 23 if(a[i]+a[j]==sum){ 24 Tuple t = new Tuple(a[i],a[j]); 25 return t; 26 } 27 } 28 } 29 return null; 30 } 31 public static void main(String[] args) { 32 double a[] = {3,8,4,9,12,5,1}; 33 double sum = 10; 34 Tuple t = find(a,sum); 35 System.out.println("數組中和為:"+sum+"的兩個數為:"+t.a+" "+t.b); 36 37 } 38 39 }程序運行結果如下:
數組中和為: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<j;){ 54 if(a[i]+a[j]==sum){ 55 Tuple t = new Tuple(a[i],a[j]); 56 return t; 57 }else if(a[i]+a[j]>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
總結
以上是生活随笔為你收集整理的第2章 数字之魅——快速寻找满足条件的两个数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kv存储对抗关系型数据库
- 下一篇: 2#两数相加