This guide outlines essential best practices spanning code style, architectural design, debugging, testing, performance, and portability—all aimed at reducing the long-term cognitive load of code maintenance. 🎨 1. Style Code is written for humans to read, and only incidentally for computers to execute. Variable Naming : Use descriptive names for global variables, and short names for local variables. Precision and Consistency : Use active names for functions (e.g., calculateTotal ). Above all, keep your coding style consistent throughout the project. Structure & Expressions : Use a consistent indentation and brace ( {} ) style to show program structure visually. Use the natural form for expressions. Use parentheses to make the semantics unambiguous. Break up overly complex expressions to keep them clear. Side Effects & Macros : Beware of functions with side effects. Avoid function-like macros; if unavoidable, parenthesize the macro body and arguments carefully. Magic Numbe...
LeetCode 解題練習:Move Zeroes
- 取得連結
- X
- 以電子郵件傳送
- 其他應用程式
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
If you like this post, please click the ads on the blog or buy me a coffee. Thank you very much.
題目原文描述 https://leetcode.com/problems/move-zeroes/
中文描述
給定一個整數陣列 nums ,將所有的 0 移到陣列結尾處,並保持原先非零整數的順序。請修改原本陣列 nums 的內容來完成。
範例一:
輸入 nums = [0, 1, 0, 5, 0, 0, 3]
輸出 nums = [1, 5, 3, 0, 0, 0, 0]
範例二:
輸入 nums = [0, 0, 1]
輸出 nums = [1, 0, 0]
範例三:
輸入 nums = [1]
輸出 nums = [1]
範例四:
輸入 nums = [0]
輸出 nums = [0]
解法一:
left = 0,從左邊開始往右移動,如果陣列元素 nums[i] 不等於零 ,則將此元素複製到 nums[left],再將 left 加 1。走訪完陣列後,left 為非零整數的數量,從left索引位置之後的元素通通設為零。
Python Code
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left = 0
for i in range(len(nums)): # 從左邊開始往右移動
if nums[i] != 0: # 陣列元素 nums[i] 不等於零
nums[left] = nums[i] # 將此元素複製到 nums[left]
left += 1 # 將 left 加 1
# left 為非零整數的數量
while left < len(nums): # 將 left 索引位置之後的元素通通設為零。
nums[left] = 0
left += 1
解法二:
找出數字零 zeroPos 的位置,然後開始往後找非零數字 nums[i] != 0 位置,將 nums[i] 與 nums[zeroPos] 交換,並更新 zeroPos 的位置。
Python Code
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeroPos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[zeroPos], nums[i] = nums[i], nums[zeroPos] # 交換
zeroPos += 1
這個網誌中的熱門文章
Solutions to Blocky Game Music (Blockly 音樂遊戲參考解法)
Solutions to Blocky Game Movie (Blockly 影片遊戲參考解法)
If you like this post, please click the ads on the blog or buy me a coffee . Thank you very much. Level 1: Level 2: Level 3: Level 4: Level 5: Level 6: Level 7: Level 8: Level 9: 若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。 If you like this post, please click the ads on the blog or buy me a coffee . Thank you very much.


留言