Remove Duplicates from Sorted Array - LeetCode
Can you solve this real interview question? Remove Duplicates from Sorted Array - Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique element ap
leetcode.com
문제
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
- Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
- Return k.
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.
오름차순으로 정렬되어있는 nums
에서 중복된 요소들을 제거하는 문제이다.
nums
배열 자체에서 제거하고, 중복된 수를 제거한 길이를 반환한다.
내 풀이
첫 번째 풀이
처음에는 간단하게 생각해서 스택을 사용해 문제를 풀었다.
직전 원소를 스택에 삽입하고, 스택에서 요소들을 peek
해서 비교한 뒤 중복을 제거했다.
class Solution {
public int removeDuplicates(int[] nums) {
Stack<Integer> stack = new Stack<>();
stack.push(nums[0]);
int k = 1;
for(int i=1; i<nums.length; i++){
if(nums[i] != stack.peek()){
nums[k] = nums[i];
stack.push(nums[i]);
k++;
}
}
return k;
}
}
- 시간복잡도 : O(n)
- 공간복잡도 : O(n)
두 번째 풀이
스택은 별도의 메모리 공간을 사용하게 되므로 공간복잡도가 O(n)이 된다.
공간 복잡도를 O(1)로 유지하면서 중복된 요소를 제거하는 방법은 없을까?
배열은 정렬되어있고 중복된 원소를 모두 제거하고 유일한 1개만 남기는 것이기 때문에 그냥 직전의 원소랑만 비교하면 되지 않을까?
class Solution {
public int removeDuplicates(int[] nums) {
int k = 1;
for(int i=1; i<nums.length; i++){
if(nums[i-1] != nums[i]){
nums[k] = nums[i];
k++;
}
}
return k;
}
}
k가 i보다 커질일은 없기 때문에 비교하는 시점에 두 개의 원소는 원래 nums
의 원소이다.
이렇게 하면 공간복잡도가 O(1)로 유지된다.
다른 사람들의 풀이를 보았는데 두 번째로 풀이한 코드와 비슷했다. 최선의 복잡도를 가지는 정답에 가까운 풀이였던 것 같다.
'알고리즘 > 자료구조' 카테고리의 다른 글
[LeetCode] 169. Majority Element - Java (0) | 2023.08.24 |
---|---|
[LeetCode] 80. Remove Duplicates from Sorted Array II - Java (0) | 2023.08.24 |
[LeetCode] 27. Remove Element - Java (0) | 2023.08.24 |
[LeetCode] 88. Merge Sorted Array - Java (0) | 2023.08.24 |
[백준] 1874 스택 수열 (스택) - Java (0) | 2023.05.16 |