Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
翻譯蒟蒻
找出在陣列中兩個相同的元素,且其索引值差值不超過 k。
Example 1:
1 2
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
1 2
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
1 2
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Solution - JavaScript
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function(nums, k) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j <= i + k && j < nums.length; j++) { if (nums[i] == nums[j]) { returntrue; } } } returnfalse };
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function(nums, k) { let map = newMap();
for(let i = 0; i < nums.length; i++) { if(map.has(nums[i]) && i - map.get(nums[i]) <= k) { returntrue; } map.set(nums[i], i); } returnfalse; };
Solution - Ruby
Solution 1: (Time Limit Exceeded)
1 2 3 4 5 6 7 8 9 10
defcontains_nearby_duplicate(nums, k) for i in0...nums.length for j in i+1...nums.length if nums[i] == nums[j] && (j - i) <= k returntrue end end end returnfalse end
Solution 2:
1 2 3 4 5 6 7 8 9 10 11
defcontains_nearby_duplicate(nums, k) hash = {} nums.each_with_index do |num, index| if hash[num] && (index - hash[num]).abs <= k returntrue else hash[num] = index end end false end