1. 程式人生 > >Contains Duplicate II

Contains Duplicate II

等於 abs urn logs ont tro cat whether code

    這道題為簡單題

  題目:

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

  思路:

    利用字典,如果該元素存在於字典中,就判斷是否這兩個的索引值的絕對值是否小於等於k,如果沒有小於就添加或更改字典的鍵值

  代碼:

 1
class Solution(object): 2 def containsNearbyDuplicate(self, nums, k): 3 """ 4 :type nums: List[int] 5 :type k: int 6 :rtype: bool 7 """ 8 b = {} 9 for i in range(len(nums)): 10 if nums[i] in b and abs(b[nums[i]] - i) <= k:
11 return True 12 b[nums[i]] = i 13 return False

Contains Duplicate II