[Leetcode] Sum 系列
Sum 系列題解
Two Sum題解
題目來源:https://leetcode.com/problems/two-sum/description/
Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int* result = (int*)malloc(2 * sizeof(int));
int i, j;
for (i = 0; i < numsSize; i++) {
for (j = 0; j < numsSize; j++) {
if (i == j) continue;
if (nums[i] + nums[j] == target) {
if (i < j) {
result[0] = i;
result[1] = j;
} else {
result[0 ] = j;
result[1] = i;
}
return result;
}
}
}
return result;
}
解題描述
這道題目還是比較簡單的,為了找到目標數字的下標,使用的是直接用雙層循環遍歷數組裏面任意兩個數的和,檢查和是否等於給定的target。之後再返回存有所求的兩個數字的下標的數組。
更優解法
2018.1.24 更新:
之前這道題的做法屬於暴力破解,時間復雜度還是較高的,達到了O(n^2),查了一些資料之後發現使用哈希可以把時間復雜度降到O(n):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
int size = nums.size();
vector<int> res(2);
for (int i = 0; i < size; i++) {
auto got = hash.find(target - nums[i]);
if (got != hash.end()) {
res[0] = got -> second;
res[1] = i;
return res;
}
hash[nums[i]] = i;
}
}
};
3Sum 題解
題目來源:https://leetcode.com/problems/3sum/description/
Description
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
Example
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Solution
class Solution {
private:
vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
vector<vector<int> > res;
int low = 0;
int high = end;
while (low < high) {
if (nums[low] + nums[high] == target) {
vector<int> sum(2);
sum[0] = nums[low++];
sum[1] = nums[high--];
res.push_back(sum);
// 去重
while (low < high && nums[low] == nums[low - 1])
low++;
while (low < high && nums[high] == nums[high + 1])
high--;
} else if (nums[low] + nums[high] > target) {
high--;
} else {
low++;
}
}
return res;
}
public:
vector<vector<int> > threeSum(vector<int>& nums) {
vector<vector<int>> res;
int size = nums.size();
if (size < 3)
return res;
sort(nums.begin(), nums.end());
for (int i = size - 1; i >= 2; i--) {
if (i < size - 1 && nums[i] == nums[i + 1]) // 去重
continue;
auto sum2 = twoSum(nums, i - 1, 0 - nums[i]);
if (!sum2.empty()) {
for (auto& sum : sum2) {
sum.push_back(nums[i]);
res.push_back(sum);
}
}
}
return res;
}
};
解題描述
這道題是Two Sum的進階,解法上采用的是先求Two Sum再根據求到的sum再求三個數和為0的第三個數,不過題意要求不一樣,Two Sum要求返回數組下標,這道題要求返回具體的數組元素。而如果使用與Two Sum相同的哈希法去做會比較麻煩。
這裏求符合要求的2數之和用的方法是,先將數組排序之後再進行夾逼的辦法。並且為了去重,需要在2sum和3sum都進行去重。這樣2sum夾逼時間復雜度為O(n),總的時間復雜度為O(n^2)。
4Sum 題解
題目來源:https://leetcode.com/problems/4sum/description/
Description
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
Example
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
Solution
class Solution {
private:
vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
vector<vector<int> > res;
int low = 0;
int high = end;
while (low < high) {
if (nums[low] + nums[high] == target) {
vector<int> sum(2);
sum[0] = nums[low++];
sum[1] = nums[high--];
res.push_back(sum);
// 去重
while (low < high && nums[low] == nums[low - 1])
low++;
while (low < high && nums[high] == nums[high + 1])
high--;
} else if (nums[low] + nums[high] > target) {
high--;
} else {
low++;
}
}
return res;
}
vector<vector<int> > threeSum(vector<int>& nums, int end, int target) {
vector<vector<int>> res;
if (end < 2)
return res;
sort(nums.begin(), nums.end());
for (int i = end; i >= 2; i--) {
if (i < end && nums[i] == nums[i + 1]) // 去重
continue;
auto sum2 = twoSum(nums, i - 1, target - nums[i]);
if (!sum2.empty()) {
for (auto& sum : sum2) {
sum.push_back(nums[i]);
res.push_back(sum);
}
}
}
return res;
}
public:
vector<vector<int> > fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int size = nums.size();
if (size < 4)
return res;
sort(nums.begin(), nums.end());
for (int i = size - 1; i >= 2; i--) {
if (i < size - 1 && nums[i] == nums[i + 1]) // 去重
continue;
auto sum3 = threeSum(nums, i - 1, target - nums[i]);
if (!sum3.empty()) {
for (auto& sum : sum3) {
sum.push_back(nums[i]);
res.push_back(sum);
}
}
}
return res;
}
};
解題描述
這道題可以說是3Sum的再次進階,使用的方法和3Sum基本相同,只是在求3個數之和之後再套上一層循環。時間復雜度為O(n^3)。
3Sum Closest 題解
題目來源:https://leetcode.com/problems/3sum-closest/description/
Description
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution
class Solution {
private:
inline int abInt(int val) {
return val >= 0 ? val : -val;
}
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size();
if (size < 3)
return 0;
sort(nums.begin(), nums.end());
int closest = nums[0] + nums[1] + nums[2];
int first, second, third, sum;
for (first = 0; first < size - 2; ++first) {
if (first > 0 && nums[first] == nums[first - 1])
continue; // 去重
second = first + 1;
third = size - 1;
while (second < third) {
sum = nums[first] + nums[second] + nums[third];
if (sum == target)
return sum;
if (abInt(sum - target) < abInt(closest - target))
closest = sum;
if (sum < target)
++second;
else
--third;
}
}
return closest;
}
};
解題描述
這道題可以說是3Sum的變形,題意上是要求在數組裏面找到三個數的和最接近target
,也就是說可能不等於target
。算法上面與3Sum的解法有一定的相似度,先固定一個位置first
,在其後進行夾逼求最接近target
的三數之和。
[Leetcode] Sum 系列