The fastest algorithm to select numerical pairs

Question: For N integers [N <= 10 ^ 5], complete pairs of integers that have the difference K. [K> 0 and K <1e9] are counted. Each of N integers will be greater than 0 and at least K from 2 ^ 31-1 (everything can be done with 32-bit integers).

1st line contains N and K (integers). The second line contains N dialing numbers. All N rooms are guaranteed to be excellent.

Now the question comes from hackerrank. I have a solution for the question, but it does not meet the deadline for all test cases. I'm not sure if another algorithm can be used, but I have no ideas. I’ll go if someone takes a little time to check my code and give advice or two.

temp = input()
temp = temp.split(" ")
N = int(temp[0])
K = int(temp[1])
num_array = input()
num_array = num_array.split(" ")
diff = 0
pairs= 0
i = 0
while(i < N):
    num_array[i] = int(num_array[i])
    i += 1
while(num_array != []):    
    j = 0
    while(j < (len(num_array)-1)):
        diff = abs(num_array[j+1] - num_array[0])
        if(diff == K):
            pairs += 1
        j += 1
    del num_array[0]
    if(len(num_array) == 1):
        break
print(pairs)
+4
2

, :

, O (n):

  • x - H [x]
  • x , x-k H, - 1,

(, ) O (nlgn)

, , , " ", 1 - H [x] * H [x + k]

, HashMap H " 0"

  • x: H [x] = H [x] +1
  • x H [x] * H [xk] ( , , , , H [xk] = 0)

- - - O (n) O (nlgn)

, numbesr A k ( ):

H=set()
ans=0
for a in A: 
  H.add(a)
for a in A: 
  if a-k in H: 
    ans+=1
print ans

H=set(A)
ans = sum(1 for a in A if a-k in H)
print ans
+5

(-).

1: D . 2: A [i] + k .

Dictionary<int> dict = new Dictionary<int>();
foreach (int n in num_array) do dict.Add(n);
int solitions = 0;
foreach (int n in num_Array) do 
  if dict.contains(n+k) 
    solutions += 1;

- O (1), - O (1). O (n). , .

, python.

EDIT: , . , . , , .

+2

All Articles