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 jis at most k.
解法1:首先想到的即是两重循环暴力破解,时间复杂度O(k*n)。
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { int n = nums.size(); if(n < 2 || k > n) return false; bool res = false; for(int i = 0; i < n; i++) { int m = n > i + k ? i + k : n - 1; for(int j = i + 1; j <= m; j++) { if(nums[i] == nums[j]) { res = true; break; break; } } } return res; } };
这个方法在数组很长时会Time Limit Exceeded。
解法2:考虑使用Hash表存储已经扫描过的元素。如果元素还没出现过,则存储下它在数组中的位置;如果已经存在,则存储下两个相同值的距离,然后判断这个距离是否小于k。
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { int n = nums.size(); if (n < 2) return false; bool res = false; map<int, int> mii; for (int i = 0; i < n; i++) { if (mii[nums[i]] == 0) { if (i == 0) mii[nums[i]] = -1; else mii[nums[i]] = i; } else { if (mii[nums[i]] == -1) mii[nums[i]] = i - mii[nums[i]] - 1; else mii[nums[i]] = i - mii[nums[i]]; if (abs(mii[nums[i]]) <= k) { res = true; break; } } } return res; } };