Contains Duplicate II

    这道题为简单题

  题目:

    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

 

posted @ 2017-09-18 20:19  唐僧洗发爱飘柔  阅读(83)  评论(0)    收藏  举报