-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_Two_Sum_python3
More file actions
33 lines (31 loc) · 1.41 KB
/
01_Two_Sum_python3
File metadata and controls
33 lines (31 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Solution_1_Brute_Force
# 20220823
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
if target - i in nums and nums.index(target - i) != nums.index(i):
return [nums.index(i), nums.index(target - i)]
# 思路: 在nums裡找符合target - i的數,且此數序號不等於i,返回i 跟 符合數的序號
# 錯誤: 若i = target - i 報錯
# 20220824
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
new_nums = copy.deepcopy(nums)
new_nums.remove(i)
if target - i in new_nums and nums.index(target - i) != nums.index(i):
return [nums.index(i), nums.index(target - i)]
# 思路: 新增new_nums,並在new_num移除i
# 錯誤: 若input[x,x]相同數值,無法判斷target-i 的序數
# 20220828
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
k = 0
for i in nums:
k = k+1
if target - i in nums[k:] :
return [nums.index(i), nums[k:].index(target - i) + k]
# 參考: https://medium.com/@havbgbg68/leetcode-1-two-sum-python-8d77c223abd3
# 思路: 設定序數k,for loop裡面在k之後尋找target - i
# Runtime: 1184 ms, faster than 32.01% of Python3 online submissions for Two Sum.
# Memory Usage: 14.9 MB, less than 76.53% of Python3 online submissions for Two Sum.