Source of https://www.interviewstreet.com/challenges/dashboard/#problem/4e14b83d5fd12
Solution report:
It is the simplest algorithm used to sort the data first, and then traverse the data from the past to the next, calculate the value + k for each number, and then look for whether the value + k exists in the second part.
#include <iostream>#include <algorithm>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; }
Appendix:
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 1363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793