Description
Given an array of integers and an integer k , find out whether there are two distinct indices i and j n the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
思路:本题是寻找数组中是否存在重复元素的升级版,在原题上需继续判断相等元素下标的差不能大于 k。考虑使用 map 数据结构,数组元素映射为 key,数组下标映射为 value,遍历数组,如果不存在相等元素就更新到 map 中,直到遍历完数组。
C++ 代码
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if (nums.size() < 2 || k < 1) return false; unordered_map<int, int> numsMap; for (int i = 0; i < nums.size(); ++i) { if (numsMap.count(nums[i]) == true) { if (i - numsMap[nums[i]] <= k) return true; else numsMap[nums[i]] = i; } numsMap.insert(pair<int, int>(nums[i], i)); } return false; } };
运行时间:32ms
运行内存:15.4M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于