該博客記錄自己刷LeetCode的過程,每道題AC后總結寫博客,希望對自己又幫助。
目前刷題使用語言為Python。LeetCode鏈接。
問題描述如下。
首先我們分析題目。
題目的意思是給任意一個數組,在給一個目標數。在數組中找到兩個數相加等于這個目標數,然后返回這兩個數的下標。題目假設數組中只有唯一的兩個數相加等于目標數,既返回的下標只有一組。
這道題屬于很簡單的題目,代碼如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
others = target - nums[i]
if others in nums:
index1 = i
index2 = nums.index(others)
if index1 == index2:
continue
else:
break
return index1,index2
根據代碼可以很明確的看到思路。我們遍歷整個List。用 target 減去第 i 個數,得到others。然后在數組中找是否存在與others相等的數。如果存在,則返回 i 和 others的下標,如果不存在,則i + 1。
思路很簡單,但是要避免一個小坑。
如果List是[3 , 3], target = 6。按照上述思路,nums[0] = 3 , others = 3, 然后在數組中找到與others相等的數后即退出循環,返回下標。我們返回的下標是[0, 0] 而實際正確的答案應該是[0, 1]。
出現這個原因是因為,我們在數組中找是否存在與others相等的數時,也包括了nums[i],如果others 和 nums[i] 相等的情況,則會返回相同的下標。
解決這個小坑的方法有很多。
我的思路是返回的判斷返回的下標,如果index1 = index2,那么這次循環不算,continue。然后進入下一次循環。
這樣[3 , 3], target = 6 返回的下標是返回的下標是[1, 0]。
這個地方我感覺有點問題,應該是[0, 1]因為continue后i + 1了,所以會出這個問題。但是同樣AC了。
解決這個小問題的思路很簡單,這種情況只出現在others == nums[i]的情況,當我們判斷這種情況出現時,我們把nums[i]的值置為無窮小,這樣不會影響結果。
修改后的代碼如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
others = target - nums[i]
if others == nums[i]:
nums[i] = -9999999
if others in nums:
index1 = i
index2 = nums.index(others)
if index1 == index2:
continue
else:
break
return index1,index2
很簡單的AC了,用時有點暴力。
以上就是本題的解題代碼和思路。很簡單的題目,如果對這種方法不滿意,也歡迎和我討論新的方法。
補充:
去做LeetCode的題目是為了提高自己的算法水平和代碼能力,基礎薄弱。有的題目雖然自己的方法可以AC,但是有更好的方法可以學習。個人認為刷題不僅是為了AC,更多的是學習新的方法和技巧。
關于本題參考了其他博客,用Python Dict的方法用時更短也更巧妙。參考博客鏈接:http://www.cnblogs.com/zuoyuan/p/3698966.html
附上新的方法的代碼:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dictTmp = {}
for i in range(len(nums)):
x = nums[i]
if target - x in dictTmp:
return (dictTmp[target-x], i)
dictTmp[x] = i
新的方法采用的是Python字典的方法。
我們首先把nums[i]的值對應的下標放在字典里。在遍歷整個nums[i]時,判斷target -
nums[i]是否在字典中,如果在字典中,則返回字典的下標,以及此時的i。
這種方法很巧妙,需要注意判斷的位置。
由于表述問題可能不是很清楚,建議有疑惑的同學自己用筆親自畫一畫或者Debug單步調試。
以上,祝好!