首页 > 其他 > 详细

leetcode Contains Duplicate II

时间:2015-12-14 23:00:50      阅读:177      评论: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 difference between i and j is at most k

 

这道题自己最后没有做出来,看的是【陆草纯】的解法。

如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。

先讲一下陆草纯的解法:

构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。

如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)

 

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> vec;
        int s=nums.size();
        if(s==0||k==0) return false;
        for(int i=0;i<s;i++){
            if(vec.find(nums[i])==vec.end()){
                vec[nums[i]]=i;
            }
            else {
                if(i-vec[nums[i]]<=k) return true;
                vec[nums[i]]=i;
            }
        }
        return false;
    }
};

 

leetcode Contains Duplicate II

原文:http://www.cnblogs.com/LUO77/p/5046501.html

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