從數組中找到 a+b=c+d 的兩個數對

  • 給定一個數組,找出數組中是否有兩個對數(a,b)和(c,d)使 a+b=c+d ,其中 a,b,c,d 是不同元素。比如: {1, 9, 23, 3, 33, 7}; 1+9 = 3+7

  • 分析:如果使用四重循環的話時間複雜度爲O(N^4) ,時間複雜度太高。下面是使用 Hash 法,通過存數對的和在哈希表中,判斷是否已經存儲過相同的和。具體代碼如下:


public class ArrayElements {

    static class Pair {
        int first, second;

        public Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }
    }

    boolean findPairs(int[] arr) {

        HashMap<Integer, Pair> hashMap = new HashMap<>();
        int n = arr.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                int sum = arr[i] + arr[j];
                if (!hashMap.containsKey(sum)) {
                    hashMap.put(sum, new Pair(i, j));
                } else {
                    Pair pair = hashMap.get(sum);
                    System.out.println("(" + arr[pair.first] + "," + arr[pair.second] + ")");
                    System.out.println("(" + arr[i] + "," + arr[j] + ")");
                    return true;
                }
            }
        }


        return false;
    }
}
  • 調用如下:
    @Test
    public void test() {
        int[] ints = {1, 9, 23, 3, 33, 7};
        ArrayElements arrayElements = new ArrayElements();
        arrayElements.findPairs(ints);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章