LeetCode刷题:Two Sum 系列

tech2023-01-25  61

Two Sum 系列

1 两数之和1.1 题目描述1.2 解法1.2.1 Python1.2.2 C++ 2 两数之和22.1 题目描述2.2 解法

1 两数之和

原题链接:Leetcode 1. 两数之和

1.1 题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

1.2 解法

1.2.1 Python

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: res = {} ans = [] for i in range(len(nums)): if nums[i] in res: ans.append(res[nums[i]]) ans.append(i) return ans res[target - nums[i]] = i return ans

1.2.2 C++

同样是hash,要用到头文件 <algorithm> 中的 find 函数来搜索。

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> res; vector<int> ans; int n = nums.size(); for (int i = 0; i < n; i ++) { if (res.find(target - nums[i]) == res.end()) { // 如果没找到 res[nums[i]] = i; //记录当前的value对应的索引 } else { // 找到了 ans.push_back(res.find(target - nums[i])->second); ans.push_back(i); return ans; } } return ans; } };

2 两数之和2

原题链接:167. 两数之和 II - 输入有序数组

2.1 题目描述

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

说明:

返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

2.2 解法

仍然是用 hash map,和之前的一样,只不过修改了一下 else if 以及返回的 +1。

class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { unordered_map<int, int> res; vector<int> ans; int n = numbers.size(); for (int i = 0; i < n; i ++) { if (res.find(target - numbers[i]) == res.end()) { res[numbers[i]] = i; } else { ans.push_back(res.find(target - numbers[i])->second + 1); ans.push_back(i+1); return ans; } } return ans; } };
最新回复(0)