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

letecode [219] - Contains Duplicate II

时间:2019-06-13 20:27:21      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:enc   style   lse   ret   insert   元素   cat   The   数组   

 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.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

题目大意

   给定数组,判断数组中是否存在nums[i]=nums[j],即重复的元素,要求下标i,j的绝对值差最小。

理  解:

  用map保存元素和最近出现的下标,若当前元素在map中,则比较两元素下标差,更新difMax为最小的差。

  difMax <= k 则满足条件。否则返回false.

代 码 C++:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int,int> m;
        map<int,int>::iterator it;
        int difMax = INT_MAX;
        for(int i=0;i<nums.size();++i){
            it = m.find(nums[i]);
            if(it == m.end()){
                m.insert(pair<int,int>(nums[i],i));
            }else{
                if(i - (it->second) < difMax){
                    //cout<<it->second;
                    difMax = i - (it->second);
                    it->second = i;
                }
            }
        }
        if(difMax>k)
            return false;
        else
            return true;
    }
};

运行结果:

  执行用时 :88 ms, 在所有C++提交中击败了17.53%的用户

  内存消耗 :15.4 MB, 在所有C++提交中击败了7.28%的用户

letecode [219] - Contains Duplicate II

标签:enc   style   lse   ret   insert   元素   cat   The   数组   

原文地址:https://www.cnblogs.com/lpomeloz/p/11018538.html

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