木又同学leetcode刷题又回来了,今年按照题目顺序刷
木又同学2020年第1篇解题报告
leetcode第1题:两数之和
https://leetcode-cn.com/problems/two-sum/
【题目】
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
【思路】
拿到题目,我们自然能想到最直接的解法,暴力破解,两层循环,时间复杂度O(n ^ 2)。
我们也可以使用hash,遍历nums数组每个元素n,如果target-n存在于hash中,则找到这样两个数,返回其下标。有一个地方需要注意,有可能两个元素值相同,比如数组中存在两个3(target为6),需要单独处理。
【代码】
python版本
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 特殊情况
half = target // 2
if nums.count(half) == 2 and half * 2 == target:
return [nums.index(half), len(nums) - 1 - nums[::-1].index(half)]
# hash
d = {}
for i, n in enumerate(nums):
d[n] = i
# 遍历
for i, n in enumerate(nums):
if n == target - n:
continue
if (target - n) in d:
return [i, d[target - n]]
C++版本
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// 暴力
vector<int> res;
for (int i=0; i<nums.size(); i++){
for (int j=i+1; j<nums.size(); j++){
if (nums[i] + nums[j] == target){
res.push_back(i);
res.push_back(j);
}
}
}
return res;
}
};
历史文章:T1-Two Sum
给我好看