6/6 每日一題(移動0)
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?
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_num=nums.count(0)#計算有幾個0
n=len(nums)#長度
i=0
while i <n-zero_num:
if nums[i]==0:
zero=nums.pop(i)
nums.append(zero)
#為了確保遺漏下一項是0的狀況,所以要再檢查一次
i -= 1
i +=1
-----參考解答
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
zero_count = 0 # 計算遇到的 0 的個數
n = len(nums)
for i in range(n):
if nums[i] != 0:
# 將非零元素向前移動 zero_count 步
nums[i - zero_count] = nums[i]
else:
zero_count += 1
# 將末尾的 zero_count 個元素設為 0
for i in range(n - zero_count, n):
nums[i] = 0
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁