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

Leetcode[219]-Contains Duplicate II

时间:2015-06-09 17:23:48      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:duplicate   leetcode   integer   indices   find   

Given an array of integers and an integer k, find out whether there 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.


分析:用map记录num和下标value,遍历数组,如果在map中存在
【mapv.find(number) != mapv.end()】并且当前位置和map中找到的位置差小于等于k【i-mapv[number] <= k】,就返回true,不然就将该值加入到map中。依次循环…

Code(c++)

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

Leetcode[219]-Contains Duplicate II

标签:duplicate   leetcode   integer   indices   find   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46427341

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