方法一:用HashMap< Integer, Integer> map,一次遍歷,判斷map中是否存在x-a[i],存在則直接返回 a[i] 和x-a[i],不然將a[i]加入map。java
方法二:排序後,從首尾出發,判斷其和code
public static void main(String[] args) { int a[] = { 1, 2, 2, 4,4, 5, 7, 11, 15 }; useHashmap(a, 15); System.out.println("------------"); useTwoPointer(a, 15); } private static void useHashmap(int a[], int x) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < a.length; i++) { if( !map.containsKey( a[i])) //添加 map.put( a[i], 1); else map.put( a[i], map.get(a[i])+1); if (map.containsKey(x - a[i])) //符合條件 if( map.get( x-a[i])>1) { for( int j=map.get( x-a[i]); j>0; j--) System.out.println( a[i] + "," + (x-a[i])); map.put( x-a[i], 1); } else System.out.println( a[i] + "," + (x-a[i])); } } private static void useTwoPointer(int a[], int x) { Arrays.sort(a); int i = 0, j = a.length - 1; while (i < j) { if (a[i] + a[j] == x) { System.out.println(a[i] + "," + a[j]); if (a[i + 1] + a[j] == x && i + 1 < j) i++; else if (a[i] + a[j - 1] == x && i < j - 1) j--; else i++; } else if (a[i] + a[j] < x) i++; else j--; } }
結果截圖:排序