黄哥Python: LeetCode 532 题K-diff Pairs in an Array

220 阅读2分钟
原文链接: zhuanlan.zhihu.com

532.K-diff Pairs in an Array 解题思路。

1、读题,数组中二数之差的绝对值为k。

2、只要遍历数组,每一个元素加上K值,还在原来的数组中,就找到一个解。

3、如果用数组遍历,会超时,通不过LeetCode 的测试,变为字典,考虑k 小于0 ,

等于0,大于0等情况。

有多人在LeetCode 中文网站上留言抱怨测试用例为啥有k 等于-1的情况。

看到有的人抱怨测试用例中为啥有k 为-1 的情况,这个正好是训练写好边界条件。

防御性编程(Defensive programming)是防御式设计的一种具体体现,它是为了保证,对程序的不可预见的使用,不会造成程序功能上的损坏。它可以被看作是为了减少或消除墨菲定律效力的想法。防御式编程主要用于可能被滥用,恶作剧或无意地造成灾难性影响的程序上。

Python 代码

# 黄哥Python培训 黄哥所写
class Solution:
    def findPairs(self, nums: List[int], k: int) -> int:
        if len(nums) == 0 or k < 0:
            return 0
        res = 0
        d = {}
        for i in nums:
            if i not in d:
                d[i] = 1
            else:
                d[i] += 1
        # print(d)
        if k == 0:
            for key in d:
                if (key + k ) in d and d[key + k] > 1:
                    res += 1
        if k > 0:
            for key in d:
                if key + k in d:
                    res += 1
        return res

Go 语言代码

// 黄哥Python培训 黄哥所写
func findPairs(nums []int, k int) int {
    if len(nums) == 0 || k < 0 {
        return 0
    }
    d := map[int]int{}
    res := 0
    for _, item := range nums {
        if val, ok := d[item]; ok {
            d[item] = val + 1
        }else {
            d[item] = 1
        }
    }
    if k == 0 {
        for _, val := range d {
            if val > 1 {
                res++
            }
        }
    }
    if k > 0 {
        for key, _ := range d {
            if _, ok := d[key + k]; ok {
                res++
            }
        }
    }
    return res
}
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标