알고리즘/LeetCode

[LeetCode/easy/Array] Remove Element

녕이 2022. 8. 16. 16:13
728x90

 

https://leetcode.com/problems/remove-element/

 

Remove Element - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

배열 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