넘치게 채우기

[LeetCode] 27. Remove Element 본문

PS/LeetCode

[LeetCode] 27. Remove Element

riveroverflow 2023. 7. 1. 12:39
728x90
반응형

 

https://leetcode.com/problems/remove-element/description/?envType=study-plan-v2&envId=top-interview-150 

 

Remove Element - LeetCode

Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then r

leetcode.com

문제 유형 : 배열

문제 난이도 : Easy

 

문제

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val 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 elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

정수형 배열 nums와 삭제할 값 val이 주어진다. nums에서 val을 모두 없앤 요소의 개수를 반환하고,배열 nums에도 val이 없어진 것이 반영되어야 정답으로 인정된다.

 

풀이

nums에 있는 val의 값들을 한번에 없애주면 된다.

 

코드(C++)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {

        nums.erase(remove(nums.begin(), nums.end(), val), nums.end());
        return nums.size();
    }
};

 

728x90
반응형