leetcode219[easy]----Contains Duplicate II

来源:互联网 发布:数据库系统设计 编辑:程序博客网 时间:2024/05/18 15:54

难度:easy

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.

思路:找到array中是否存在两个数,这两个数相同,且index之差小于或等于K。

          无数惨痛教训证明用双循环肯定是找死,一定会超时。

           把nums中的每个element转变为dict的key,index转化为dict的value。

           此题要注意这样的例子:[1,0,2,1,1,4] ,k=1,要排除掉array转dict时,数值相同,但是两个数的index相差大于k的情况。