-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pairs - Search - Algorythms.py
66 lines (51 loc) · 1.21 KB
/
Pairs - Search - Algorythms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
You will be given an array of integers and a target value. Determine the number of pairs of array elements
that have a difference equal to a target value.
Dick Stada - March 2019
"""
def pairs(k, arr): # k is target value
pairs = 0
arr = sorted(arr)
i = 0
j = 1
while j < len(arr):
diff = arr[j] - arr[i]
if diff == k:
pairs += 1
j += 1
elif diff > k:
i += 1
else: # diff < k
j += 1
return pairs
if __name__ == '__main__':
nk = input().split()
n = int(nk[0])
k = int(nk[1])
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
print(result)
"""https://www.hackerrank.com/challenges/pairs/problem
input:
5 2
1 5 3 4 2
output:
3
Varianten:
def pairs(k, arr): # k is target value
# sort arr:
arr = sorted(arr)
pairs = 0
for i in range(len(arr) - 1):
for j in range(1 + i, len(arr)):
if arr[j] - arr[i] == k:
pairs += 1
break
return pairs
def pairs(k, arr): # k is target value
pairs = 0
for getal in arr:
if getal + k in arr:
pairs += 1
return pairs
"""