LeetCode) Remove Element

gyuΒ·2024λ…„ 4μ›” 10일

Algorithm

λͺ©λ‘ 보기
15/45

πŸ“ Description

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.
Return k.

My code:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = nums.count(val)
        for i in range(k):
                nums.remove(val)
        return len(nums)

πŸ”— How to Solve

Intuition

The objective is to remove all occurrences of the element 'val' from the list 'nums' in-place and return the count of elements in 'nums' that are not equal to 'val'.

Approach

First, I thought about how to remove all occurrance of the element(val). I used count() to get the number of occurrance of the val. And I used remove() using for loop to remove all val.I then return the length of nums.

Complexity

  • Time complexity: O(n^2)
    each for loop and remove() has O(n)
    for loop needs to run n times
    remove() needs to search through the list to find the element to remove
    +) count() is also O(n)
  • Space complexity: O(1)

βœ” Tips to improve

 class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        k = 0
        for i in range(len(nums):
               if nums[i] != val:
               		nums[k] = nums[i]
                    k += 1
        return k
profile
#TechExplorer πŸš€ Curious coder exploring the tech world, documenting my programming journey in a learning journal

0개의 λŒ“κΈ€