Solution to Triangle by codility

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.