Interviewstreet-pairs-category search

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.