算法积累001
package com.bleum; /** * * @author aaron.hu * 一个排好序的数组,找出两数之和为m的所有组合 */ public class AlgorithmSample001 { public Integer[] arr = new Integer[]{1,2,3,8,10,13,19,22,23,30,32,34,35,36,37,40,42,44,46,47,50,55}; int count=0, sum = 56; //propose1设置一个中间变量,如果有满足条件的i,j,则后面的遍历的范围会大于a[i]并且小于a[j] public void launch(){ count=0; int j=arr.length-1; int flag = arr.length-1; for(int i=0; i<flag; i++){ for(j=flag; j>i; j--){ count++; if(arr[i]+arr[j]==sum){ System.out.println("arr[i]="+arr[i]+",arr[j]="+arr[j]); flag = --j; break; } } } System.out.println("Count="+count); } //propose2卡住一个端,左端只有小于M/2,右端大于M/2才会判断 public void launch2(){ count=0; for (int i = 0; i < arr.length; i++) { if (arr[i] <= 56 / 2) { for (int j = i + 1; j < arr.length; j++) { if (arr[j] >= 56 / 2) { count++; if (arr[i] + arr[j] == 56) { System.out.println(arr[i] + ":" + arr[j]); } } } } } System.out.println("Count="+count); } }
Result:
arr[i]=1,arr[j]=55
arr[i]=10,arr[j]=46
arr[i]=19,arr[j]=37
arr[i]=22,arr[j]=34
Count=80
1:55
10:46
19:37
22:34
Count=117
相关推荐
湾区人工智能 2020-11-20
Pokemogo 2020-11-16
baijingjing 2020-11-16
baijingjing 2020-11-15
Site 2020-11-07
lwnylslwnyls 2020-11-06
justaipanda 2020-11-05
MachineIntellect 2020-11-02
xueyuediana 2020-10-30
GeraldJones 2020-10-30
Tips 2020-10-29
baijingjing 2020-10-28
baijingjing 2020-10-27
硕鼠 2020-10-26
playoffs 2020-10-26
scuyxi 2020-10-25
playoffs 2020-10-25
yise001 2020-10-23