1. 程式人生 > >【Leetcode_總結】532. 陣列中的K-diff數對 - python

【Leetcode_總結】532. 陣列中的K-diff數對 - python

連結:https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/description/

Q:

給定一個整數陣列和一個整數 k, 你需要在數組裡找到不同的 k-diff 數對。這裡將 k-diff 數對定義為一個整數對 (i, j), 其中 i  j 都是陣列中的數字,且兩數之差的絕對值是 k.

示例 1:

輸入: [3, 1, 4, 1, 5], k = 2
輸出: 2
解釋: 陣列中有兩個 2-diff 數對, (1, 3) 和 (3, 5)。
儘管陣列中有兩個1,但我們只應返回不同的數對的數量。

思路:k小於0 返回0; 等於0 返回陣列中重複的值數量 ;大於0計算能夠使得相減等於k的數量 第一次使用list超時 換為字典後通過 但是效率很低

超時: 

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k == 0:
            res = 0
            temp = list(set(nums))
            for t in temp:
                if nums.count(t) > 1:
                    res += 1
            return res
        if k > 0:
            res = 0
            temp = []
            for i in range(len(nums)):
                if nums[i] + k in nums and nums[i] not in temp :
                    res += 1
                    temp.append(nums[i])
            return res
        if k < 0:
            res = 0
            return res

通過: 

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k < 0:
            return 0
        dict4nums = {}
        for i in range(len(nums)):
            if nums[i] in dict4nums:
                dict4nums[nums[i]] += 1
            else:
                dict4nums[nums[i]] = 1
        if k == 0:
            res = 0
            for value in dict4nums:
                if dict4nums[value] > 1:
                    res += 1
            return res
        if k > 0:
            res = 0
            temp = []
            for i in range(len(nums)):
                if nums[i] + k in dict4nums and nums[i] not in temp:
                    res += 1
                    temp.append(nums[i])
            return res

稍微改一下:

class Solution(object):
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k < 0:
            return 0
        dict4nums = {}
        for i in range(len(nums)):
            if nums[i] in dict4nums:
                dict4nums[nums[i]] += 1
            else:
                dict4nums[nums[i]] = 1
        if k == 0:
            res = 0
            for value in dict4nums:
                if dict4nums[value] > 1:
                    res += 1
            return res
        if k > 0:
            res = 0
            temp = list(set(nums))
            for i in range(len(temp)):
                if temp[i] + k in dict4nums:
                    res += 1
            return res