A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
- A[P] + A[Q] > A[R],
- A[Q] + A[R] > A[P],
- A[R] + A[P] > A[Q].
For example, consider array A such that:
A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20
Triplet (0, 2, 4) is triangular.
Write a function:
int solution(const vector<int> &A);
that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. For example, given array A such that:
A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20
the function should return 1, as explained above. Given array A such that:
A[0] = 10 A[1] = 50 A[2] = 5 A[3] = 1
the function should return 0.
Assume that:
- N is an integer within the range [0..1,000,000];
- each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
- expected worst-case time complexity is O(N*log(N));
- expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
又是一个简单题,但是我再次很争气的没有一次做到bug free,因为我忽略了两条边的和可能超过MAX_INT这么一件重要的事情(明明题目里都说了each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].)
吸取教训:一定要注意会不会超出范围,用minus来代替sum防止这种事情的发生!
// you can also use includes, for example: #include <algorithm> int solution(const vector<int> &A) { // write your code in C++98 int size = A.size(); if(size<3) return 0; vector<int> array(A); sort(array.begin(),array.end()); for(int i=0;i<size-2;i++) { if(array[i]<=0) continue; if(array[i]>array[i+2]-array[i+1]) { return 1; } } return 0; }