您的位置:首页 > 大数据 > 人工智能

CareerCup The number of pairs (x, y) of distinct elements with condition x + y <= Threshold

2014-03-01 18:47 651 查看
Problem1: You have a lists with integers. Find all the pairs of numbers that sum less than or equal to to a particular number k. The
list contains minimum 5 Million number.

(I provided a n^2logn solution but they may be looking forward to having a better answer).

----------------------------------------------------------------------------------------

Problem2:
Input - array of integers size N, integer Threshold. Output - the number of pairs (x, y) of distinct elements with condition x + y <= Threshold. Is that possible to implement it with O(n) ?

---------------------------------------------------------------------------------------

// perform radix sort - O(n). now the array is sorted Or quicksort, O(n) is difficult
// now, remove duplicates if you wish. and now perform the following algorithm
int i(0), j(n-1), ans(0);
while (i < j)
{
       if (a[i] + a[j] <= threshold ) {
                ans += (j-i);
                i++; 
       }
       else { j--; } 
}
return ans;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐