알고리즘/해시
[HackerRank] Pairs (PYTHON)
VIPeveloper
2021. 10. 29. 00:07
728x90
반응형
문제
Given an array of integers and a target value, determine the number of pairs of array elements that have a difference equal to the target value.링크
Example
There are three values that differ by : , , and . Return .
Function Description
Complete the pairs function below.
pairs has the following parameter(s):
- int k: an integer, the target difference
- int arr[n]: an array of integers
입력
- The first line contains two space-separated integers and , the size of and the target value.
The second line contains space-separated integers of the array .
반환값
- int: the number of pairs that satisfy the criterion
제한
- 2 <= n <= 105
- 0 < k < 109
- 0 < arr[i] < 231 - 1
- each integer arr[i] will be unique.
기록이유
- 부르트 포스로 풀이하였는데 완벽한 풀이방법이 아니라고 나왔다.
def pairs(k, arr):
# Write your code here
cnt = 0
for i in range(0,len(arr)-1):
for j in range(i+1,len(arr)):
if abs(arr[i]-arr[j]) == k:
cnt += 1
return cnt
찾아보니까 해시, 이분탐색을 이용하여 풀이하였다.링크
728x90
반응형