algorithm

27. Remove Element

rkawk 2025. 3. 21. 16:45

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

Intuition

Inplace๋กœ ๋ณ€ํ™˜์„ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ถ”๊ฐ€์ ์ธ ๋ณ€์ˆ˜ ์„ ์–ธ์„ ํ•˜์ง€ ์•Š๊ณ  ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

Approach

๋ฐฐ์—ด์˜ ํƒ์ƒ‰๊ณผ ๋ฌด๊ด€ํ•œ idx ํฌ์ธํ„ฐ๋ฅผ ์žก์•„ ๋ฐฐ์—ด์˜ ์›์†Œ ์ค‘ val๊ณผ ๋‹ค๋ฅธ ์›์†Œ๊ฐ€ ๋‚˜์˜ฌ ๊ฒฝ์šฐ idx์— ์ €์žฅํ•˜๋„๋ก ๊ตฌํ˜„ํ•˜์˜€๋‹ค.

 

Inplace์˜ ๋ชฉ์ ์— ๋งž๊ฒŒ ๋ฐฐ์—ด์— ๋Œ€ํ•œ ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์ด ํ•„์š” ์—†๋„๋ก ๊ตฌํ˜„ํ•˜์˜€๋‹ค.

Complexity

- Time complexity : O(N)

- Space complexity : O(1)

 

Code

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int K = 0, idx = 0;
        for(auto e : nums) {
            if(e != val) {
                nums[idx] = e;
                idx += 1;
                K += 1;
            }
        }
        return K;
    }
};

'algorithm' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

๋ฐฑ์ค€ 3190  (0) 2025.03.30
๋ฐฑ์ค€ 12100 (์‚ผ์„ฑ ๊ธฐ์ถœ)  (0) 2025.03.28
DP - ์•„์ดํ…œ์„ ์ ์ ˆํžˆ ๊ณ ๋ฅด๋Š” ๋ฌธ์ œ  (0) 2025.03.21
935 div2 C. Manhattan Permutations  (0) 2024.08.07
๋ฐฑ์ค€ 2671  (0) 2024.08.02