leetcode #1 #15 #16 #18 #167 K-Sum Problem Solution
阿新 • • 發佈:2019-02-15
Problem Description
- Given an array S of n integers, are there any k elements in S such that a[1]+a[2]+..+a[k] = target? Find all unique quadruplets in the array which gives the sum of target.
Some Details
- #1 k=2 and target=0, return the index, the solution is unique
- #15 k=3 and target=0
- #16 k=3, return the sum which is closest to the target
- #18 k=4
- #167 == #1 (O(n) is required)
Solution
#1 2個數的和。 (1)列舉每一對數,加加看 O(n^2)慢嗎? (2)如果有序的話,取a[l],a[r]為首尾數,若a[l]+a[r]<target,l++,若a[l]+a[r]>target,r--,否則,找到了。O(n) 正確性是顯然的。那麼排序時間O(nlgn)即為時間複雜度 #15 3個數的和。 (1)列舉任意三個數,加加看 O(n^3),太慢了? (2)a[i]+a[j]=-a[k],如果a[i]是個常數的話,c+a[j]=-a[k],問題變為2個數的和,先有序O(nlgn)後處理O(n)。怎麼把a[i]變常數?列舉一下i,這樣整體複雜度O(n^2) #16 最近的,和#15一樣的題呀。 #18 多列舉一維,也是一個道理。O(n^3) #167 喵喵喵?#1(2)
Code
//隨便貼兩個吧
//#167
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int> ans;
int len=numbers.size();
int i=0,j=len-1;
while (i<j)
{
if (numbers[i]+numbers[j]>target) j--; else
if (numbers[i]+numbers[j]<target) i++; else
{
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
}
return ans;
}
};
//#16
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int siz=nums.size(),i=0,j,k;
int ans=nums[0]+nums[1]+nums[2];
sort(nums.begin(),nums.end());
while (i<siz-1)
{
j=i+1; k=siz-1;
while (j<k)
{
int now=nums[i]+nums[j]+nums[k];
if (abs(target-now)<abs(target-ans)) ans=now;
if (now==target) return target;
if (now>target && j<k) k--; else
if (now<target && j<k) j++;
if (j>=k) break;
//j++; k--;
}
i++;
}
return ans;
}
};