Computer Science/코딩테스트
LeetCode #26 Remove Duplicates from Sorted Array
Seongwoo
2022. 7. 12. 10:37
문제
내림차순으로 정렬된 정수 배열 번호가 주어지면 각 고유 요소가 한 번만 나타나도록 중복을 제자리에서 제거합니다. 요소의 상대적 순서는 동일하게 유지되어야 합니다.
일부 언어에서는 배열의 길이를 변경할 수 없으므로 결과를 배열 nums의 첫 번째 부분에 배치해야 합니다. 더 공식적으로, 중복을 제거한 후 k 요소가 있으면 nums의 처음 k 요소가 최종 결과를 보유해야 합니다. 처음 k개 요소를 넘어 무엇을 남겨두는지는 중요하지 않습니다.
nums의 처음 k 슬롯에 최종 결과를 배치한 후 k를 반환합니다.
다른 어레이에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리를 사용하여 제자리에서 입력 배열을 수정하여 이 작업을 수행해야 합니다.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
- 1 <= nums.length <= 3 * 104
- -100 <= nums[i] <= 100
- nums is sorted in non-decreasing order.
제출코드
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (i < nums.length - 1 && nums[i] == nums[i + 1]) {
continue;
}
nums[count] = nums[i];
count++;
}
return count;
};
풀이
해당 문제는 아주 심플하다. 우선 정렬된 배열이 주어진다. 그럼 우리는 인접한 인덱스의 정수값이 같은지만 확인하고
다르다면 해당값은 하나밖에 없는것이기 때문에 주어진 배열에 0번인덱스부터 값을 다시 대입해준다.