[leetcode] 219. Contains Duplicate II

来源:互联网 发布:ie浏览器不能登陆淘宝 编辑:程序博客网 时间:2024/06/15 21:43

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的相等元素,题目难度为Easy。

题目和第217题相关,大家可以先看下第217题(传送门)。重复元素的判断还依靠Hash Table,遍历数组,如果当前元素之前没有相同元素将其加入Hash Table;如果有相同元素,判断二者下标差,不超过k则返回true,超过k则更新该元素在Hash Table中记录的下标为当前下标,以便后续继续比较使用。具体代码:

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