Fixed logarithm of HackerRank Algorithms-Search-Pairs Array

Source: Internet
Author: User

I made a few questions in HackerRank, so let's talk about it... Question: Give n and k, then give n numbers, and find the number of k pairs in the array. Where [N <= 10 ^ 5], [K> 0 and K <1e9], all numbers are in the int range. Obviously, it will definitely time out if it is naked. (Although HackerRank seems to have no time limit, the faster the score, the higher the score ...) In another way, traverse the array and query whether the number + k exists. If the number exists, the total number is + 1. set is used for storage and query. The complexity is log (n ), the overall complexity is nlog (n), which should be much faster. Code:

  /*  *   Author:        illuz <iilluzen[at]gmail.com>  *   Blog:          http://blog.csdn.net/hcbbt  *   File:          pairs.cpp  *   Lauguage:      C/C++  *   Create Date:   2013-09-06 09:06:47  *   Descripton:    pairs, sort   */  #include <cstdio>  #include <set>  using namespace std;  #define rep(i, n) for (int i = 0; i < (n); i++)  #define FI(i, x) for (typeof((x).begin()) i = (x).begin(); i != (x).end(); i++)    set<int> m;    int main() {      int n, k, t;      scanf("%d%d", &n, &k);      rep(i, n) {          scanf("%d", &t);          m.insert(t);      }      int cnt = 0;      for (set<int>::iterator i = m.begin(); i != m.end(); i++) {          t = *i;          if (m.count(t + k))             cnt++;         }      printf("%d\n", cnt);      return 0;  }  

 


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.