本文主要介绍LeetCode上“Two Sum”类问题的分析及解决方法。
1 问题概述
对于“Two Sum”类问题,基本要求为:给定一个整数数组,在该数组中找到两个元素,这两个元素之和等于给定的数字(target),返回这两个元素的索引(下标)值。
2 解题思路
对于这类“Two Sum”题目,一般有以下两种解决方法:
- 对于无序数组,借助unordered_map等容器存储数组元素,并以“unordered_map元素==target-数组元素”为目标进行求解;
- 对于有序数组,设置数组左、右元素,并以“数组做元素+数组右元素==target”为目标进行求解。
3 问题示例
3.1 无序数组
3.1.1 题目描述
1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:Input: nums = [3,3], target = 6
Output: [0,1]
3.1.2 解决方案
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++) {
int complm = target - nums[i];
if (m.count(complm)) {
res.push_back(m[complm]);
res.push_back(i);
break;
}
else
{
// store elements of nums
m[nums[i]] = i;
}
}
return res;
}
};
3.2 有序数组
3.2.1 题目描述
167. Two Sum II - Input Array Is Sorted
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
3.2.2 解决方案
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int i = 0;
int j = numbers.size() - 1;
while (i < j) {
if (numbers[i] + numbers[j] == target) {
res.push_back(i + 1);
res.push_back(j + 1);
break;
}
else if (numbers[i] + numbers[j] < target) {
i++;
}
else {
j--;
}
}
return res;
}
};