본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 27. Remove Element

반응형

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

간단 전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

n이 작기 때문에 2차원 loop를 수행해 정렬해도 됩니다.

📔 풀이과정

지울 수를 배열의 뒷편에 배치시키는 swap문제라고 생각해봅니다.

앞의 val이 있다면 그 이후부터 for loop를 수행하며 val이 아닌 원소를 찾아 swap을 해주면 됩니다.

📔 정답출력

val이 아닌 원소들의 길이를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] != val) continue;
            for(int j = i+1; j < nums.size(); j++){
                if(nums[j] == val) continue;
                swap(nums[i], nums[j]);
                break;
            }
        }
        int cnt = 0;
        for(auto n: nums) {
            if(n == val) break;
            cnt++;
        }
        return cnt;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.