【朱迪的LeetCode刷题笔记】】283. Move Zeroes #Easy #Python
本帖最后由 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 =
Output:
Example 2:
Input: nums =
Output:
Constraints:
1 <= nums.length <= 104
-231 <= nums <= 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
: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( * x)
Python beats 18.76%
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List
: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
:rtype: None Do not return anything, modify nums in-place instead.
"""
count=nums.count(0)
nums[:]=
nums+=*count
Sol2
Python beats 59.6% #TwoPointers
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List
:rtype: None Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums != 0 and nums == 0:
nums, nums = nums, nums
# wait while we find a non-zero element to
# swap with you
if nums != 0:
slow += 1
Sol3
Python beats 87.64% (better than Sol2!) #TwoPointers
class Solution(object):
def moveZeroes(self, nums):
n = len(nums)
i = 0
for j in range(n):
if (nums != 0):
nums, nums = nums, nums
i += 1
我写过这题hh
class Solution:
def moveZeroes(self, nums: List) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = 0
j = 0
while j < n:
if nums != 0:
nums , nums = nums , nums
i += 1
j += 1 还有这个,这是我第一次写的,投机取巧了,上面那个是看了答案有双指针再去写的
class Solution:
def moveZeroes(self, nums: List) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
a = nums.count(0)
for i in range(a):
nums.remove(0)
nums.append(0)
yinda_peng 发表于 2023-6-6 19:10
还有这个,这是我第一次写的,投机取巧了,上面那个是看了答案有双指针再去写的
hhhh 我也这么写了 yinda_peng 发表于 2023-6-6 19:05
我写过这题hh
这个你可以展开讲讲吗 Judie 发表于 2023-6-7 21:47
这个你可以展开讲讲吗
差不多就是跟答案那个双指针一样的,i表示当前已经处理好的非0元素的最后一位,j表示当前处理到的位置。如果nums不等于0,就将其交换到nums的位置上,然后i向后移动一位,继续处理下一个元素
yinda_peng 发表于 2023-6-7 19:52
差不多就是跟答案那个双指针一样的,i表示当前已经处理好的非0元素的最后一位,j表示当前处理到的位置。 ...
噢噢噢噢 明白了 谢谢
页:
[1]