Question:https://codility.com/programmers/lessons/4
We need, parts to prove, our solution.
On one hand,there is no false triangular. Given The array has been sorted, if a[i]+a[i+1]>a[i+2], we can prove the existence of the triangle. For array A are sorted, we can easily confirm that a[i+2] + a[i] > a[i+1] and a[i+1]+a[i+2] >a[i]. So we just need to check this condition.
On the other hand,There is no underreporting triangular.If The inequality can hold for three out-of-order elements, to say, A[index]+a[index+m] > A[index+n], where n>m>1 . Because array A is sorted, we can reach that A[index+m-1]>=a[index] and a[index+n]>= A[index + m+1]; After simplification, we infer that a[index+m-1]+a[index+m] > a[index+m+1].If we have any inequality holding for out-of-order elements, wemust haveAt LEASTAn inequality holding for three consecutive elements.
Some trap:
- Forget to check a[i] >0;
- Need to judge if A.size () <3; Rather than left these to the condition on for loop. Because A.size () return size_t type. If A.size () ==1,a.size ()-2 may get A very large positive num, than leads to error.
C + + Solution
#include <algorithm> #include <vector> #include <map>int solution (vector<int> &a) { // Write your code in C++11 if (a.size () <3) return 0; Sort (A.begin (), A.end ()); for (int i=0; i< a.size () -2&& i<a.size (); i++) { if (a[i]>0 && a[i]>a[i+2]-a[i+1]) return 1; } return 0;}
Solution to Triangle by codility