leetcode219---Contains Duplicate II

来源:互联网 发布:淘宝女童模特 编辑:程序博客网 时间:2024/06/17 00:51

问题描述:

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.

具有相同的数,并且下标相差不超过k。

问题求解:

方法一:

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        int n=nums.size();        unordered_map<int, int> um;        for(int i=0;i<n;i++)        {            if(um.find(nums[i]) != um.end() && abs(um[nums[i]] - i) <= k)                return true;            um[nums[i]] = i;//比如[1,0,1,1],每个数字对应一个唯一的hash映射!!!        }        return false;    }};

方法二:

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        int n=nums.size();        unordered_map<int, int> um;        unordered_map<int, int>::iterator iter;        for(int i=0;i<n;i++)        {            iter = um.find(nums[i]);            if(iter != um.end() && abs(iter->second - i) <= k)                return true;            um[nums[i]] = i;//比如[1,0,1,1],每个数字对应一个唯一的hash映射!!!        }        return false;    }};
0 0