Friday, June 10, 2016

Triangle Count -- LintCode

Question:
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?
Example
Given array S = [3,4,6,7], return 3. They are:
[3,4,6]
[3,6,7]
[4,6,7]

Answer:
2 pointer: Time:O(n*n)
public int triangleCount(int S[]) {
        // write your code here
        Arrays.sort(S);
        int len = S.length;
        int count = 0;
        for(int k=len-1;k>=2;--k){
            int i=0;
            int j=k-1;
            while(i<j){
                if(S[i] + S[j] > S[k]){
                    //keep j, k, i is a valid segment. Count all the eles in segment ([i,j-1],  j,k)
                    count += j-i;
                    j--;
                }else{
                    //S[i] + S[j] <= S[k]
                    i++;
                }
            }
        }
        return count;
    }

No comments:

Post a Comment