Contains Duplicate II
Posted 唐僧洗发爱飘柔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Contains Duplicate II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode219. Contains Duplicate II