Problem:
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.
Summary:
给出数组nums,整型数k,找到数组中是否存在nums[i]和nums[j]相等且i - j小于k的情况。
Solution:
开始用最简单写法,两重for循环逐一查找,出现TLE。
后用HashMap改进,key为数组中出现的数字,value为最近出现位置的下标。
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 int len = nums.size(); 5 unordered_map<int, int> m; 6 7 for (int i = 0; i < len; i++) { 8 if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) { 9 return true; 10 } 11 else { 12 m[nums[i]] = i; 13 } 14 } 15 16 return false; 17 } 18 };