码迷,mamicode.com
首页 > 其他好文 > 详细

Solution of NumberOfDiscIntersections by Codility

时间:2015-06-02 23:27:23      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:programming   algorithm   

question:https://codility.com/programmers/lessons/4


trap: int overflow


code:

#include <algorithm>
int solution(vector<int> &A) {
    // write your code in C++11
    int size = A.size();
    if (size <2)
        return 0;
    vector<long> begin;
    vector<long> end;
    for(int i=0; i<size; i++){
        begin.push_back(i-static_cast<long>(A[i]));
        end.push_back(i+static_cast<long>(A[i]));
    }
    sort(begin.begin(),begin.end());
    sort(end.begin(),end.end());
    int res = 0;
    int upper_index =0, lower_index=0;
    for(upper_index =0; upper_index<size; upper_index++){
        while(lower_index<size && begin[lower_index]<= end[upper_index])
            lower_index++;
        res += lower_index-upper_index-1;
        if (res >10000000)
            return -1;
    }
    return res;
}


Solution of NumberOfDiscIntersections by Codility

标签:programming   algorithm   

原文地址:http://blog.csdn.net/chenlei0630/article/details/46337047

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!