首页 > 其他 > 详细

Contains Duplicate II

时间:2017-09-18 21:27:03      阅读:175      评论:0      收藏:0      [点我收藏+]

    这道题为简单题

  题目:

    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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!