Contains Duplicate II

来源:互联网 发布:威纶通触摸屏编程手册 编辑:程序博客网 时间:2024/05/29 19:06

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.
思路:哈希表问题,代码如下:

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