December 22, 2023

Viiisit [LeetCode] - 219. Contains Duplicate II

#php#javascript#ruby

keep learning, keep coding!

Problem - Contains Duplicate II

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。


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]) {
return true;
}
}
}
return false
};

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 = new Map();

for(let i = 0; i < nums.length; i++) {
if(map.has(nums[i]) && i - map.get(nums[i]) <= k) {
return true;
}
map.set(nums[i], i);
}

return false;
};

Solution - Ruby

Solution 1:
(Time Limit Exceeded)

1
2
3
4
5
6
7
8
9
10
def contains_nearby_duplicate(nums, k)
for i in 0...nums.length
for j in i+1...nums.length
if nums[i] == nums[j] && (j - i) <= k
return true
end
end
end
return false
end

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
def contains_nearby_duplicate(nums, k)
hash = {}
nums.each_with_index do |num, index|
if hash[num] && (index - hash[num]).abs <= k
return true
else
hash[num] = index
end
end
false
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
function containsNearbyDuplicate($nums, $k) {
$map = [];

for ($i = 0; $i < count($nums); $i++) {
if (isset($map[$nums[$i]]) && $i - $map[$nums[$i]] <= $k) {
return true;
}
$map[$nums[$i]] = $i;
}

return false;
}

LeetCode 傳送門 - Contains Duplicate II