LeetCode[219] Contains Duplicate II

来源:互联网 发布:js实现旋转 编辑:程序博客网 时间:2024/04/30 20: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.


建立哈希表,值为下标,顺序遍历nuns元素,若发现相等元素,计算 i - hash[nums[i]],若满足则返回true。若大于k,更新hash[nums[i]],因为 i 的值只会越来越大,先前的下标值已经没有意义了。

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;hash[nums[i]] = i;}return false;}};

0 0
原创粉丝点击