Ruby O(n) solution with minimum numbers of swaps


  • 1
    A

    Unlike solutions with swapping elements this one does as little swaps as possible.

    def remove_element(nums, val)
        l = 0
        r = nums.size - 1
        while l <= r
          if nums[r] == val
            r -= 1
          elsif nums[l] == val
            nums[l] = nums[r]
            l += 1
            r -= 1
          else
            l += 1
          end
        end
        
        r + 1
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.