leetcode 219. Contains Duplicate II

来源:互联网 发布:松下fp系列编程手册 编辑:程序博客网 时间:2024/04/29 22:31

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:

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






0 0
原创粉丝点击