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

219. Contains Duplicate II

时间:2016-03-16 01:46:38      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:contains duplicate

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 jis at most k.


解题思路:

用一个表,记录扫描过程中,每个数字出现的最近

一次位置,则当前位置和最近位置的差小于k时 返回true,

bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int size=nums.size();
        if(size<=1||k<=0)
            return false;
        
        unordered_map<int,int> table;
        
        for(int i=0;i<size;++i){
            auto it=table.find(nums[i]);
            if(it==table.end())
                table[nums[i]]=i;
            else{
                if(i-table[nums[i]]<=k)
                    return true;
                it->second=i;
            }
        }
        return false;
    }



219. Contains Duplicate II

标签:contains duplicate

原文地址:http://searchcoding.blog.51cto.com/1335412/1751329

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