检查三元组是否为三角形?

时间:2018-02-22 08:52:34

标签: java

我的解决方案有1次测试失败。 https://app.codility.com/demo/results/trainingU5HYHS-MDC/

import java.util.Arrays;

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
             if(A.length<3)
            return 0;

       Arrays.sort(A);

       for(int i=0;i<A.length-2;i=i+1)
       {
           if(  A[i]+A[i+1]>A[i+2]  )
           {
               return 1;
           }

       }

       return 0;
    }
}

但是这个解决方案已经通过100%,但我不明白为什么 https://app.codility.com/demo/results/trainingYKT8FB-TAV/

class Solution {
    /**
     * Check whether there is a triangular
     * @param A         The array for length of lines
     * @return          0: no triangular found
     *                  1: triangular is found
     */
    public int solution(int[] A) {
        // Handle with the special cases
        if(null == A || A.length < 3) return 0;

        // Sort the input, and then try to find the triangular
        Arrays.sort(A);
        for(int i = 0; i < A.length-2; i++) {
            // Beware of overflow
            if (A[i] >= 0 && A[i] > A[i+2] - A[i+1]) {
                return 1;
            }
            /*
             * We already know A[i+1] <= A[i+2]. If A[i] < 0,
             * A[i] + A[i+1] < A[i+2]
             */
        }
        return 0;
    }
}

2 个答案:

答案 0 :(得分:2)

使用2个值时,您的代码会失败>可以将整数分配给最大值。

.send()行中你正在添加。如果超过整数限制,则会遇到整数溢出。

其他代码通过从不进行这样的添加来避免这种情况。

答案 1 :(得分:1)

不平等规则:
其中指出:三角形边长小于另外两边长度之和,大于另外两边长度之差。

如果我们通过边a + b > c

如果A[I] + A[I+1]的总和大于int的容量,则overflow成为A[I] + A[I+1] < 0A[I] + A[I+1] not greater than A[I+2] =&gt;的结果if( A[i]+A[i+1]>A[i+2] )

此处false在发生溢出时返回if (A[i + 2] >= 0 && A[i + 2] > A[i + 1] - A[i]) or if (A[i] >= 0 && A[i] > A[i+2] - A[i+1])

所以,最好使用,

var salary number
var empname varchar2(10)
create or replace procedure emp_lookup
(no IN emp55.empno%TYPE,
salary OUT emp55.sal%TYPE,
empname OUT emp55.ename%TYPE)
IS
begin
select sal , ename INTO salary, empname
from emp55
where empno=no;

EXCEPTION WHEN NO_DATA_FOUND THEN empname:='null';
salary:=-1;

execute emp_lookup (3346, :salary,:empname);
print salary