Leetcode - Remove Element

Leetcode - Remove Element

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

Daily Leetcode

Hits

๋ฌธ์ œ ๋งํฌ

ํŠน์ • ์›์†Œ๋ฅผ ์ง€์šฐ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๊ฑด ์‚ฌ์‹ค Naive๋ฅผ ์ƒ๊ฐํ•˜๋Š”๊ฒŒ ๋” ์–ด๋ ค์šด ๋ฌธ์ œ์ด๋‹ค.

ํ•ต์‹ฌ์€ in-place ์—์„œ ์‚ญ์ œ๊ฐ€ ์ด๋ค„์ ธ์•ผ ํ•œ๋‹ค. ๊ทธ๋Ÿผ ๊ฒฐ๊ตญ ํฌ์ธํ„ฐ๋ฅผ ์“ธ ์ˆ˜ ๋ฐ–์—..

๐Ÿฅฝ Solution

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:

        n = len(nums)
        idx = 0

        for i in range(n) :
            if nums[i] != val:
                nums[idx] = nums[i]
                idx += 1
        
        return idx
            

์ง€์›Œ๋„ ๋˜์ง€ ์•Š์€ ์›์†Œ๋ผ๋ฉด ์•ž์—์„œ๋ถ€ํ„ฐ ์ฑ„์›Œ๋„ฃ์–ด์ค€๋‹ค. ๊ทธ๊ฒŒ ์•„๋‹ˆ๋ผ๋ฉด ๊ทธ๋ƒฅ ๋ฌด์‹œํ•˜๊ณ  ๋„˜์–ด๊ฐ€๋ฉด์„œ idx๋ฅผ ์ฑ„์›Œ ์ฃผ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.

๐Ÿ‘ป Complexity

  • Time : O(n)
  • Space : O(1)