复习C++和python语法,以后准备渐渐用python刷leetocde.
题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。
思路
利用哈希表建立键值对值——位置,一边遍历数组,一边建立哈希表。找到target数对结束。
时间复杂度: O(n)
空间复杂度: O(n)
代码
C++版本:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> val_pos;
vector<int> res(2, -1);
for(int i = 0; i < nums.size(); i++)
{
if(val_pos.count(target-nums[i]) > 0)
{
res[0] = i;
res[1] = val_pos[target-nums[i]];
break;
}
val_pos[nums[i]] = i;
}
return res;
}
};
python版本
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
val_pos = {}
for i, num in enumerate(nums):
if target - num in val_pos:
return [i, val_pos[target-num]]
val_pos[num] = i
#将下面一行注释掉后,提升4ms左右
#return []
相关用法
C++语法:map.count(value) 查看哈希表中键为value的值的个数。
python语法:用到了 enumerate 和 key in dict .