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; }