Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?

Solution: 最大的一边作为target,a[j] + a[k] > a[i]

    public int triangleCount(int S[]) {
        if(S == null || S.length < 3){
            return 0;
        }
        Arrays.sort(S);
        int ans = 0;
        for(int i = S.length - 1; i > 1; i--){
            int j = 0;
            int k = i - 1;
            while(j < k){
                if(S[j] + S[k] <= S[i]){
                    j++;
                } else{
                    ans += k - j;
                    k--;
                }
            }
        }
        return ans;
    }

results matching ""

    No results matching ""