???????開始學(xué)習(xí)算法挑社,到leetcode上找題目練手陨界,第一題就是兩數(shù)之和,難度標(biāo)注為簡單痛阻,想了一段時(shí)間才想出來菌瘪,差點(diǎn)以為腦子太久沒用秀逗了,之后繼續(xù)做三數(shù)之和阱当,沒能全靠自己想出來俏扩,還是參考了一下別人的想法。
三數(shù)之和代碼
???????三數(shù)之和參考了這里:http://www.reibang.com/p/19b0261c73b9斗这,不知道是不是編程語言的差別动猬,如果按原思路走會超出時(shí)間限制,所以代碼思路改了幾個(gè)地方表箭。
總體思路赁咙,為避免遺漏需要遍歷每個(gè)數(shù)字,為避免重復(fù)免钻,按順序往后挑選彼水。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
count = len(nums)
collect = []
for i in range(count):
left = i+1
right = count-1
#避免重復(fù)找同一個(gè)數(shù)據(jù)
if i >0 and nums[i] == nums[i-1]:
left +=1
continue
#數(shù)據(jù)按小到大排列,每次選取nums[i]极舔,在其后尋找符合a + b + c = 0的兩個(gè)數(shù)據(jù)
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum == 0:
col = [nums[i],nums[left],nums[right]]
collect.append(col)
left+=1
right-=1
#循環(huán)中nums[i]已確定凤覆,當(dāng)再確定1個(gè)數(shù)時(shí),另一個(gè)數(shù)也確定拆魏,左右端任一端出現(xiàn)重復(fù)均可跳過
while nums[left] == nums[left-1] and left < right:
left+=1
while nums[right] == nums[right+1] and left < right:
right-=1
if sum<0:
left+=1
elif sum > 0:
right-=1
return collect
兩數(shù)之和代碼
???????排好順序之后盯桦,根據(jù)大小關(guān)系慈俯,縮進(jìn)數(shù)字左右端范圍,然后再從原始數(shù)據(jù)的副本里尋找數(shù)字對應(yīng)序號拥峦。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_copy = nums.copy()
nums.sort()
front = 0
end = len(nums) - 1
while end>front:
if nums[front]+nums[end]>target:
end -=1
elif nums[front]+nums[end]<target:
front+=1
else:
first = nums_copy.index(nums[front])
#如果first和second相等贴膘,可能會找到同一個(gè)序號,所以設(shè)置為None
nums_copy[first] = None
second = nums_copy.index(nums[end])
return first,second
????leetcode里兩數(shù)之和耗時(shí)最短的代碼利用差值和字典略号,思維簡潔而精確刑峡;三數(shù)之和耗時(shí)最短的代碼利用了除0以外正負(fù)數(shù)相加才會等于零的關(guān)系,劃分正負(fù)數(shù)玄柠,按條件選韧幻巍;用好數(shù)學(xué)關(guān)系確實(shí)能使代碼高效不少羽利。