HackerRank Pairs
https://www.hackerrank.com/challenges/pairs/problem
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
import itertools
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
def pairs(k, arr):
# Write your code here
arr.sort()
# arr is not sequence
ans = 0
for i in itertools.combinations(arr, 2):
if (abs(i0 - i1) == k):
ans += 1
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
def pairs(k, arr):
s = set(arr)
ans = 0
for v in arr:
if v + k in s:
ans += 1
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
def pairs(k, arr):
# Write your code here
sarr = set(arr)
ans = 0
for n in arr:
if n - k in sarr:
ans += 1
if n + k in sarr:
ans += 1
return ans // 2
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
提出
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'pairs' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY arr
#
# 1 5 3 4 2 k=2
#
# - Have to avoid O(n)^2
# - Set(1 5 3 4 2)
# - If arri + k in Set O(1) => ans += 1
def pairs(k, arr):
s = set(arr)
ans = 0
for v in arr:
if v + k in s:
ans += 1
return ans
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0)
k = int(first_multiple_input1)
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()