LeetCode 1.兩數之和-簡單
1.題目
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那兩個整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。
示例
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2.解題
方法一:暴力破解-耗時甚至超時
- 拿數組的第i個數和後面的數相加,判斷是否等於target。其中i從1開始直到n-1, n是數組長度。 一旦等於target了,就返回那兩個數字所在的下標
- 複雜度分析:
時間複雜度 O(Nˆ2): 因爲使用了2層循環
空間複雜度 O(1)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[i] + nums[j] == target:
return [i, j]
方法二:使用數組的in和index方法
- 利用數組的in方法和List的index方法
- 遍歷數組的數nums[i],通過in方法**target-num[i]**判斷是否在數組內,如果在,則使用index方法獲得下標。(注意要判斷是否是使用了重複的元素)
class Solution:
def twoSum(self, nums, target):
length = len(nums) # 數組長度
for i in range(length): # 遍歷數組
if target - nums[i] in nums: # 判斷target-nums[i]是否在nums數組中
j = nums.index(target - nums[i])
if j != i: # 如果j不等於i, 說明沒有重複利用元素
return [i, j]
方法三:用字典提高查詢效率
此方法參考圖解答案。
- 遍歷的過程中將數組存入字典中,查詢操作在字典上進行,能提高速度
- 複雜度分析:
時間複雜度 O(N):只遍歷了一次算法
空間複雜度 O(N):構建了一個新的字典
class Solution:
def twoSum(self, nums, target):
s = {} # 構建字典
length = len(nums) # 數組長度
for i in range(length): # 遍歷數組
if target - nums[i] in s: # 在集合中根據key值查找
return [s[target - nums[i]], i]
else:
s[nums[i]] = i # 集合s中的key值存放數組值,方便查找,value值存放下標