算法面试题:一个数组,找出两数之和为m的所有组合
public static void main(String[] args) { int[] list = {1,2,3,4,5,6,7,8,9,10,11,23,45,55,66,77,88,99,24}; int limit = 9; arraySort(list); methodA(list,limit); }
public static void methodA(int[] list,int limit){ int s = 0; int e = list.length -1; while (list[e] > limit){ e--; } while (e > s){ int r = list[s]+list[e]; if(r == limit){ System.out.println(list[s]+"+"+list[e]+"="+limit); s++; e--; }else if(r > limit){ e--; }else if(r < limit){ s++; } } }
public static int[] arraySort(int[] list){ int temp; for (int i =0; i<list.length;i++){ for (int j = i ;j<list.length;j++){ if(list[i]>list[j]){ temp = list[i]; list[i]=list[j]; list[j]=temp; } } } System.out.println(Arrays.toString(list)); return list; }
还可以有另外一个思路:
public static void methodB(int[] list,int limit){ int s =0; int e = list.length-1; while (list[e] > limit) e--; while (e>s){ for (int i =0 ;i<e;i++){ if (list[i]+list[e]==limit) System.out.println(list[i]+"+"+list[e]+"="+limit); } e--; } }