码迷,mamicode.com
首页 > 其他好文 > 详细

Contains Duplicate II

时间:2017-09-18 22:11:56      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:hat   题目   ica   索引   array   ret   turn   eth   def   

    这道题为简单题

  题目:

    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

标签:hat   题目   ica   索引   array   ret   turn   eth   def   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7544953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!