给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
作为一个从来不考虑执行时间的用户来说,第一时间就给出了一个复杂度很高的答案:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for index in range(len(nums)):
if (index+1 != len(nums)):
for anotherIndex in range(index+1, len(nums)):
if (nums[index] + nums[anotherIndex] == target):
result.append(index)
result.append(anotherIndex)
break
return result
系统的最后一个测试用例用的数又多,又长,这种算法导致计算超时。
所以想到了第二个方案:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
hashMap = {}
for index in range(len(nums)):
hashMap[nums[index]] = index
for index in range(len(nums)):
temp = target - nums[index]
try:
resultIndex = hashMap[temp]
if (nums[index] != temp):
result.append(index)
result.append(resultIndex)
break
except:
pass
return result
第二个方案主要是用哈希表的思想,减少一次循环,但是如果[3,3] 6这种情况就GG了。
苦于没有第三个想法,看到了一篇博客,思路简单到令人发指,这个答案太棒了,自愧不如:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for k, i in enumerate(nums):
if target - i in nums[k + 1:]:
return [k, nums[k + 1:].index(target - i) + k + 1]
c++代码:
这个方法效率太低
class Solution {
public:
vector twoSum(vector& nums, int target) {
for (int i = 0; i < length; i++) {
int num = target - nums[i];
for (int j = i+1; j < length; j++) {
if (nums[j] == num) {
result.push_back(j);
result.push_back(i);
}
}
}
return result;
}
};
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map m;
for (int i = 0; i < nums.size(); ++i) {
if (m.count(target - nums[i])) {
return {i, m[target - nums[i]]};
}
m[nums[i]] = i;
}
return {};
}
};
第二个代码效率爆棚
参考博客:https://blog.csdn.net/xiaoxiaodechongzi/article/details/80537205
https://www.cnblogs.com/grandyang/p/4130379.html