python Leetcode刷題小記【No.1 兩數之和】
阿新 • • 發佈:2018-11-28
Leetcode 1
題目描述:
給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解法一:
''' 蠻力法:兩層迴圈,暴力求解--7560ms ''' class Solution0: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = [] for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: result.append(i) result.append(j) return result
解法二:
''' 改進1:單層迴圈--1360ms ''' class Solution1: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = [] for i in range(len(nums)): second_num = target-nums[i] if second_num in nums: j = nums.index(second_num) if i != j: result.append(i) result.append(j) return result
解法三:
''' 改進2:利用字典--48ms ''' class Solution2: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = [] index_dict = {nums[i]:i for i in range(len(nums))} for i in range(len(nums)): temp =target-nums[i] j = index_dict.get(temp) if temp in index_dict and i != j : result.append(i) result.append(j) return result
附:
# 發現先定義列表 result
result = []
# 然後append 之後再返回的效率比直接返回高 return [i,j]
result.append(i)
result.append(j)
return result