马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Judie 于 2023-6-4 21:33 编辑
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up:
Could you minimize the total number of operations done?
Judy
Python beats 28.67%class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
x = nums.count(0)
for i in range(x):
nums.remove(0)
nums.extend([0] * x)
Python beats 18.76%class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for x in nums:
if x == 0:
nums.remove(0)
nums.append(0)
Sol1
Python beats 76.93%class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=[i for i in nums if i != 0]
nums+=[0]*count
Sol2
Python beats 59.6% #TwoPointersclass Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0 and nums[slow] == 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
# wait while we find a non-zero element to
# swap with you
if nums[slow] != 0:
slow += 1
Sol3
Python beats 87.64% (better than Sol2!) #TwoPointersclass Solution(object):
def moveZeroes(self, nums):
n = len(nums)
i = 0
for j in range(n):
if (nums[j] != 0):
nums[i], nums[j] = nums[j], nums[i]
i += 1
|