How to know that a triangle triple exists in our array?

后端 未结 13 1355
[愿得一人]
[愿得一人] 2020-12-04 16:52

I was stuck in solving the following interview practice question:
I have to write a function:

int triangle(int[] A);

that given a zero-

相关标签:
13条回答
  • 2020-12-04 17:36
    public static int solution(int[] A) {
        // write your code in Java SE 8
        long p, q, r;
        int isTriangle = 0;
    
        Arrays.sort(A);
        for (int i = 0; i < A.length; i += 1) {
    
            if (i + 2 < A.length) {
                p = A[i];
                q = A[i + 1];
                r = A[i + 2];
                if (p >= 0) {
                    if (Math.abs(p) + Math.abs(q) > Math.abs(r) && Math.abs(q) + Math.abs(r) > Math.abs(p) && Math.abs(r) + Math.abs(p) > Math.abs(q))
                        return 1;
                }
            } else return 0;
    
    
        }
    
        return isTriangle;
    
    }
    

    The above implementation is Linear in time complexity. The concept is simple use the formaula they gave extracting a series of triplets of sorted elements.

    0 讨论(0)
提交回复
热议问题