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 解題練習:Check If N and Its Double Exist
- 取得連結
- 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/check-if-n-and-its-double-exist/
中文描述
給定一個整數陣列 arr,找出陣列中兩個不一樣位置的元素是不是符合 arr[i] * 2 = arr[j],其中 i != j。
範例一:
輸入 arr = [-1, 8, 2, 1, 4]
輸出 true
因為元素 4 是元素 2 * 2。
範例一:
輸入 arr = [-1, 8, 3, 1, 4]
輸出 false
因為沒有任一兩個元素符合 arr[i] * 2 = arr[j],其中 i != j。
解法一:
先排序,在用二分搜尋法找有沒有目前陣列元素兩倍的數字出現在不同的索引位置。
Python Code
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
arr.sort()
count = len(arr)
for i in range(count):
pro = arr[i] * 2
left = 0
right = len(arr) - 1
while left <= right:
middle = (left + right) // 2
if arr[middle] == pro and i != middle:
return True
elif arr[middle] > pro:
right = middle - 1
else:
left = middle + 1
return False
解法二:
使用 hastTable 來儲存陣列的每一個元素 ele,在每次加入一個元素時檢查 ele * 2 與 ele / 2 是否有在 hashTable 出現過,若有,回傳 true。在加完陣列的每一個元素之後,回傳 false。
Python Code
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
hashTable = {}
for ele in arr:
if ele * 2 in hashTable or ele / 2 in hashTable:
return True
hashTable[ele] = 0
return False
這個網誌中的熱門文章
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.
留言