interviewstreet-pairs --类别search

题目来源:https://www.interviewstreet.com/challenges/dashboard/#problem/4e14b83d5fd12

解题报告:

就是用的最简单的算法,先排序,再从前往后依次遍历,对每个数算出value+K的值,往后二分查找是否存在value+K。

#include 
#include 
using namespace std;

int main()
{
    int N, K;
    cin >> N >> K;
    long long *key = new long long[N];

    for (int i = 0; i < N; i++)
    {
        cin >> key[i];
    }
    sort (key, key+N);
    int k = 0;
    for (int i = 0; i < N; i++)
    {
        int begin = i+1;
        int end = N-1;
        int value = key[i] + K;
        while(begin <= end)
        {
            int mid = (begin+end)/2;
            if (key[mid] < value)
                begin = mid + 1;
            else if (key[mid] > value)
                end = mid - 1;
            else
            {
                k++;
                break;
            }
        }
    }
    cout << k << endl;
    
}


附录:

Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]

Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.

Sample Input #00:
5 2
1 5 3 4 2

Sample Output #00:
3

 
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 


你可能感兴趣的:(interviewstreet-pairs --类别search)