06.28.2024
0. Before We Begin
I write my code even though my code is ridiculous as is the question just in case someone wonders what the heck is going on and why the judging seems odd.
1. Problem
2. My Code
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
const s = new Set(nums);
const result = [...s];
const k = nums.length;
nums.length = 0;
result.forEach((n)=>{nums.push(n);});
return k;
};
I used Set to take only distinct numbers out.
As the judging process didn't let me pass this despite the right result(seemingly), I set the nums.length = 0 and put each element of result.
I don't know why it worked but it was suggested by one commentor.
3. What This Problem Really Wanted
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let lastValue = nums[0];
let nextIdx = 1;
for(let i = 1; i < nums.length; i++){
if(nums[i] !== lastValue) {
nums[nextIdx] = nums[i];
lastValue = nums[i];
nextIdx++;
}
}
return nextIdx;
};
What this problem wanted you to do was to sort the numbers at the front whenever you face each distinct number.
The return type was also confusingly written so was the description.
The funny thing is the first code worked much faster.
'CS > algorithm' 카테고리의 다른 글
[LeetCode] 169. Majority Element (0) | 2024.06.27 |
---|---|
[LeetCode] 78. Subsets (0) | 2024.01.29 |
[LeetCode] 446. Arithmetic Slices II - Subsequence (0) | 2024.01.08 |
[LeetCode] 46. Permutations (0) | 2024.01.03 |
1912 연속합 with 파이썬 (feat. DP, 동적 프로그래밍) (0) | 2023.08.18 |