Open bonfy opened 5 years ago
解法1 - 暴力法
两重遍历, 时间复杂度 O(n²)
class Solution:
def twoSum(self, nums, target):
L = len(nums)
for i in range(i, L):
for j in range(i+1, L):
if nums[i] + nums[j] == target:
return [i, j]
解法2 - Hash
一重遍历, 时间复杂度 O(n)
class Solution:
def twoSum(self, nums, target):
dct = {}
for num in nums:
if num in dct:
return [num, dct[num]]
else:
t = target - num
dct[t] = num
这里 Leetcode 是假设给定的测试用例肯定有解,严谨点应该在最后加上,表示没有解的情况
return [-1, -1]
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Leetcode: Two Sum - https://leetcode.com/problems/two-sum/