当前位置:网站首页>Daily question 2006 Number of pairs whose absolute value of difference is k

Daily question 2006 Number of pairs whose absolute value of difference is k

2022-07-05 05:42:00 A big pigeon

topic : Given array nums And integer k, In the array Satisfy |nums[i]-nums[j]| = k(i<j) Number to number .

Explain :1. Direct double cycle

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        cnt = 0
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if abs(nums[j]-nums[i]) == k:
                    cnt += 1
        return cnt

2. Hashtable

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        cnt, ans = Counter(nums), 0
        for key in cnt:
            if (key + k) in cnt:
                ans += cnt[key] * cnt[key + k]                
        return ans

原网站

版权声明
本文为[A big pigeon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140620422337.html