80. Remove Duplicates from Sorted Array II
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
감소하지 않는 순서로 정렬된 정수 배열 nums가 주어지면, 각 고유 요소가 최대 두 번 나타나도록 중복을 제자리에서 제거합니다. 요소의 상대적 순서는 동일하게 유지해야 합니다.
일부 언어에서는 배열의 길이를 변경할 수 없으므로 대신 결과를 배열 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,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
- 1 <= nums.length <= 3 * 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in non-decreasing order.
코드
- l (쓰기 포인터) : 수정된 배열의 새로운 길이를 결정하는 포인터
- r (읽기 포인터) : 배열을 순회하면서 현재 값을 읽어오는 포인터
class Solution {
fun removeDuplicates(nums: IntArray): Int {
var l = 0
var r = 0
while (r < nums.size) {
var count = 1
while ((r + 1 < nums.size) && (nums[r] == nums[r + 1])) {
r++
count++
}
for (i in 0 until minOf(2, count)) {
nums[l] = nums[r]
l++
}
r++
}
return l
}
}
'LeetCode > Two Pointers' 카테고리의 다른 글
[LeetCode][Kotlin] 557. Reverse Words in a String III (0) | 2024.10.19 |
---|---|
[LeetCode][Kotlin] 1768. Merge Strings Alternately (0) | 2024.10.19 |
[LeetCode][Kotlin] 844. Backspace String Compare (0) | 2024.10.01 |