728x90
https://leetcode.com/problems/remove-element/
배열 nums와 원소 val이 주어지는데, nums 내에서 val 값인 원소 모두 삭제
STL vector의 함수들을 사용하면 되는데, remove와 erase가 있다. 이 둘의 가장 큰 차이점은
remove는 값을 삭제하는 것이 아니다. 맨 뒤로 보내는 것이다. 그러고 뒤로 보내진 애들의 가장 첫 번째 원소 인덱스를 반환한다.
erase는 값을 삭제한다. 대신, 원소를 인자로 받아서 삭제하는 것이 아니라 범위 내의 원소들을 삭제하는 것이다.
즉, remove는 vector의 사이즈가 변경되지 않고 erase는 변경된다.
erase와 remove를 함께 사용하면 삭제된다^^ 이전 문제와 비슷하게 진행!
int removeElement(vector<int>& nums, int val) {
nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
return nums.size();
}
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/Array] Plus One (0) | 2022.08.16 |
---|---|
[LeetCode/easy/Array] Search Insert Position (0) | 2022.08.16 |
[LeetCode/easy/Array] Remove Duplicates from Sorted Array (0) | 2022.08.16 |
[LeetCode/easy] Ransom Note (0) | 2022.08.12 |
[LeetCode/easy] Reverse Vowels of a String (0) | 2022.08.12 |