Problem solving/LeetCode
[LeetCode] 26. Remove Duplicates from Sorted Array (C++)
겸
2023. 6. 30. 23:20
문제
non-decreasing 순서로 정렬된 정수 배열이 주어진다.
각 요소가 한번만 나타나도록 중복 항목을 제자리에서 제거하기
다른 순서는 동일하게 유지되어야 한다.
남은 고유 숫자의 개수와 제거된 배열 구하기
생각할 것
- set을 사용해보자
a. set에 모든 값을 넣고 중복된 값이 제거된 set을 num에 할당하기
b. num의 크기를 리턴하기
c. 이 방법은 메모리가 좀 더 필요하다. - 또 다른 방법
a. nums[i] ≠ nums[i-1] 일 경우 앞으로 당겨서 대입하기
코드
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
set<int> s;
for(int i=0; i<nums.size(); i++){
s.insert(nums[i]);
}
nums.assign(s.begin(), s.end());
return nums.size();
}
};
반응형