Solution of NumberOfDiscIntersections by Codility

Posted brucemengbm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Solution of NumberOfDiscIntersections by Codility相关的知识,希望对你有一定的参考价值。

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


this question is seem like line intersections question. we can use similar method to solve this question. 

now i prove this solution. for each line, it has two endpoint. we call it left and right. assume that  the left and right have been sorted . 

if line i and line j intersection, we can conclude that left[i]<right[j] or left[j]<right[i]. ...  how to say??  

 

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的主要内容,如果未能解决你的问题,请参考以下文章

the solution of CountNonDivisible by Codility

Family of Solution Sets

Lintcode380 Intersection of Two Linked Lists solution 题解

Lintcode14 First Position of Target Solution 题解

[Solution] 893. Groups of Special-Equivalent Strings

[Solution] 985. Sum of Even Numbers After Queries