leetcode 1 :Two Sum
题目链接: https://leetcode-cn.com/problems/two-sum/
难度: 简单
归类 : 数组操作,hashmap
题目
给定一个整数数组 nums和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法
主要使用c++和python等两种语言进行了解答,以及经典题解和尝试改进的最优/最简洁解法。
个人解法
C++解法
//c++解法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hashmap;
vector<int> res(2,0);
for(int i = 0; i < nums.size(); i++){
if(hashmap.find(target - nums[i]) != hashmap.end()){
res[0] = hashmap[target - nums[i]];
res[1] = i;
return res;
}else{
hashmap[nums[i]] = i;
}
}
return res;
}
};
时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :16 ms, 在所有 C++ 提交中击败了69.92%的用户
内存消耗 :8 MB, 在所有 C++ 提交中击败了100.00%的用户
python解法
#python解法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = [0] * 2
dict_hash = {}
for i in range(len(nums)):
if (target - nums[i]) in dict_hash:
res[0] = dict_hash.get(target - nums[i])
res[1] = i
return res
else:
dict_hash.update({nums[i]: i})
return res
时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :64 ms, 在所有 Python3 提交中击败了60.83%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户
题解优解
此题有三种解法:
暴力法(O(N^2),O(1)),两遍哈希表(O(N),O(N)),一遍哈希表(O(N),O(N))
附上一个简洁的python版本。
#python解法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
"""这样写更直观,遍历列表同时查字典"""
dct = {}
for i, n in enumerate(nums):
if target - n in dct:
return [dct[target - n], i]
dct[n] = i
时间复杂度: O(N)
空间复杂度: O(N)
提交结果:
执行用时 :80 ms, 在所有 Python3 提交中击败了49.78%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户
尝试改进的最优解法
本题较为简单,无更优解法