Algorithm 第四版課後習題1.4.15(2)

一.題目內容: 對已排序數組進行 three-sum-faster
二.實現方式:
首先將數組進行排序,然後設置三個指針,位置爲數組頭部(lo),數組尾部(hi)和數組尾部-1(k),然後計算三個數相加的結果:
1.如果相加的結果大於0,則說明右邊的兩個數之和明顯大於左邊的,則將k–.
2.如果相加的結果小於0,則說明左邊的數負的太厲害,所以lo++.
3.如果相加結果爲0,則要找到有多少三個相同的pair然後計算有多少種排列組合.
4.完成一次k的循環以後,還要將lo=0,hi–,k=hi-1.

public static int threeSumFaster(int[] a){
        int count = 0;
        Arrays.sort(a);
        int lo = 0;
        int hi = a.length-1;
        int k = hi-1;
        while(a[hi]>0){
            while(k>lo){
                int result = a[lo]+a[hi]+a[k];
                if(result>0){
                    k--;
                }else if(result<0){
                    lo++;
                }else{
                    count++;
                    int sl = lo;
                    int sk = k;
                    while(a[++lo] == a[sl] && lo<k){
                        count++;
                    }
                    while(a[--k] == a[sk] && k>sl){
                        count++;
                    }   
                }   
            }
            hi--;
            k=hi-1;
            lo = 0;
        }
        return count;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章