(1) Two Sum
題目:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
給定一個list和target,找到list中加起來等于target的索引,不能重復使用值,
我的答案:
def twoSum1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
sub = target - i
nums_copy = nums.copy()
nums_copy.remove(i)
if sub in (nums_copy):
index_i = nums.index(i)
index_j = nums.index(sub,index_i+1)
break
return [index_i, index_j]
遇到的問題:
- 怎么解決“不允許重復值”:拷貝一個list;獲取索引時從index_i+1開始找,
參考答案1:
def twoSum(self, nums, target):
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i
更好的處理了不能重復使用相同值的問題:
- 邏輯:找當前值和出現在他之前的值之和,有沒有等于target的,
- 這個地方建立了一個hashmap,相當于字典啦,不過不是一次性建立的,可以解決“一個值不能用兩次的問題”,
參考答案 2:
class Solution:
def twoSum(self, nums, target):
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
這個地方把list轉成了dict,然后也用了hashmap的思路,
識訓:
- list變數獲取索引:
num.index(i), - list 變數洗掉元素
nums.remove(i),回傳的是NoneType,所以直接用nums就好啦, - list直接賦值就是物件的參考(別名);淺拷貝(copy):拷貝父物件,不會拷貝物件的內部的子物件,
- list轉dictionary,需要利用
enumerate(將一個可遍歷的資料物件(如串列、元組或字串)組合為一個索引序列):dict(list(enumerate(nums))),也可以直接for i, num in enumerate(nums), - hashmap的形式查找,可以避免出現重復值,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334115.html
標籤:其他
