codility: Triangle

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;
}

 

转载于:https://www.cnblogs.com/parapax/p/3637810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值