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

Contains Duplicate II

时间:2018-03-25 22:17:50      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:question   diff   思路   near   span   map   ica   find   cto   

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.

 找两个相等数的间距,间距最大为k,我的思路就是用map来保存index,看代码吧:)

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

        return false;
    }
};

 

Contains Duplicate II

标签:question   diff   思路   near   span   map   ica   find   cto   

原文地址:https://www.cnblogs.com/jiadyang/p/8647209.html

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