219. Contains Duplicate II

来源:互联网 发布:信贷审批业务流程优化 编辑:程序博客网 时间:2024/06/05 23:00

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.

思路:
就是设定一个哈希表,每个键存的是下标,然后遍历数组,对于每个数来说,假如是之前有存到map里的,就比较map的value和数的下标看是否小于k,假如是没有的,那么就更新map的键里面的内容。

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        if(nums.size()==0||k==0) return false;        map<int,int> maps;        for(int i=0;i<nums.size();i++)        {            if(maps.find(nums[i])==maps.end())                maps[nums[i]]=i;            else            {                if(i-maps[nums[i]]<=k)                    return true;                else                    maps[nums[i]]=i;            }        }        return false;    }};
0 0
原创粉丝点击