1. 程式人生 > >leetcode練習 532 python實現(字典方式和二分搜尋)

leetcode練習 532 python實現(字典方式和二分搜尋)

題532

題目要求在一個list中尋找差為固定值的pair的數量,具體如下:
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won’t exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].

這個結果是很好實現的,但是會發現時間複雜度始終是O(n2),所以始終通過不了。後來利用python中的字典HashMap的思想,查詢鍵值只需要O(1)的複雜度,對程式進行了改進,效果明顯提升。
我的思路是:
1.K<0,返回0
2.K=0,先對nums進行set,找到不重複的元素,再對這些元素遍歷,count它們出現的次數,若>1,說明有一個符合要求,sum+=1,最後返回sum
3.K>0, 先對nums進行set,以及sorted排序,for迴圈,建立一個dict,它的key是當前數nums[i]+k,它的值是nums[i],然後判斷當前nums[i]是不是之前出現的某個數的key,若是,則出現了一對符合要求的pair,sum+=1,最後返回sum。

程式碼如下:

class Solution:
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """

        sum =0
        nu= {}
        if k<0:
            return 0
        if k!=0:
            nums = list(set(nums))
            nums = sorted(nums)
            for
i in range(len(nums)): nu[nums[i]+k] = nums[i] if nums[i] in nu.keys(): sum+=1 return sum else: nums1 = list(set(nums)) for i in nums1: if nums.count(i)>1: sum+=1 return sum nums=[1,1,1,2,1] k=1 s= Solution() print(s.findPairs(nums,k))

結果如下:
這裡寫圖片描述

Accept結果:
這裡寫圖片描述

思路2 二分查詢

我的思路是:重要的一點是用二分搜尋尋找nums[i]+k降低時間複雜度,同時分k=0和k!=0的情況具體分析。
k=0時,需要找相等的數字對,重點是一個去重的實現。
k!=0時的去重,只要之前遇到的相同的數就continue掉,並且在找到第一個符合條件的nums[i]後就continue,不再繼續尋找。

具體程式碼如下:

class Solution:
    def findPairs(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if len(nums)==0:
            return 0
        nums.sort()
        sum = 0
        s = nums[0]
        flag = 0

        if k ==0:
            for i in range(len(nums)):
                if k == 0:
                    if i > 0 and nums[i] == s:
                        flag = 1
                    if (flag == 1 and nums[i] != s) or (flag ==1 and i==len(nums)-1):
                        flag = 0
                        s = nums[i]
                        sum += 1
            return sum

        if k != 0:
            for i in range(len(nums)-1):
                if i > 0 and nums[i] == nums[i - 1]:
                    continue
                left = i
                right = len(nums)
                while (left <= right):
                    mid = int((left + right) / 2)
                    if mid < len(nums):
                        if nums[i] + k > nums[mid]:
                            left = mid + 1
                        if nums[i] + k < nums[mid]:
                            right = mid - 1
                        if nums[i] + k == nums[mid]:
                            sum += 1
                            break
                    else:
                        break
            return sum


nums=[1,1,1,1,1,2,2,2]
k=0
s= Solution()
print(s.findPairs(nums,k))

最終也能Accept