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 |