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 解題練習:Remove Element
- 取得連結
- 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/remove-element/
中文描述
給定一個整數陣列 nums 與一個整數 val,將 nums 中的所有 val 給移除,並回傳 nums 中不等於 val 的個數k有多少個。
範例一:
輸入 nums = [1, 1, 2, 5, 3, 1, 4], val = 1
輸出 k = 4, nums [2, 5, 3, 4, x, x, x]
因為 nums 不等於 1 的總共有 4 個。
範例二:
輸入 nums = [1, 1, 2, 2, 5, 3, 1, 4], val = 2
輸出 k = 5, nums [1, 1, 5, 3, 1, 4, x, x]
因為 nums 不等於 2 的總共有 5 個。
解法一:
用 Python List 的內建函式 remove。
Python Code
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
解法二:
將變數 k 設為 0,用來判斷 nums 內有幾個元素是不等於 val。
若陣列元素不等於 val,就將 k 當成 nums 的索引,並更新元素的值。
可參考底下圖片動畫說明
Python Code
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for n in nums:
if n != val:
nums[k] = n
k += 1
return k
這個網誌中的熱門文章
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.

留言