def twoSum(self, nums:[int], target: int):
# 以 for 寫兩層巢狀 for 去尋找 第一層數字 = i
length = len(nums)
ans = [int]*2
for i in range(length):
# 1.target_num = target 數字 減去 第一層巢狀 for 的值
target_num = target - nums[i]
ans[0] = i
# 2-1. 如果其數字 等於第一層巢狀 for 值 則 跳下一個數字
for j in range(length):
if i == j:
continue
# 2-2. 如果其target_num = num2 即找到答案 return num2 ,index2
if nums[j] == target_num:
ans[1] = j
return ans
print('No answer for this problem')
return ans
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
# 用 Dict 去紀錄數字
numMap = {}
for i in range(len(nums)):
"""
當target - nums[i] 包含字典內記錄之key,
則使用get去拿到此key的value 也就是index
"""
if numMap.__contains__(target-nums[i]):
return [numMap.get(target-nums[i]), i]
# 如果沒有包含在字典內則作dict的新增 key為數字 value 為 index
else:
numMap[nums[i]] = i
php
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$res = [];
$sum = $target;
foreach ($nums as $index => $value) {
$sum = $target;
$sum -= $value;
// 如有吻合 return
if (in_array($sum, $nums)) {
$n1 = $index;
$n2 = array_search($sum, $nums);
if ($n1 !== $n2) {
$res[] = $n1;
$res[] = $n2;
return $res;
}
}
}
}
}
LeetCode
sum
[TOC] 台泥 1101 亞泥 1102 食品(傳產) 大成(飼料47%, 肉品20%) 1210 統一 1216 泰山 1218
Jul 19, 2020Contents [TOC] Hot Key in codepen Ctrl+D 可選取同一個字詞 (先用滑鼠選) Ctrl+/ comment Ctrl+L whole line select Tab indent Shift+Tab cancel indent
Feb 28, 2020or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up