*以下代码通过时间为2016.9
一.Two Sum:https://leetcode.com/problems/two-sum/
这道题目需要注意的两个问题:
1.超时
2.当是这样一个数组是[0,4,3,0] target=0时,需要注意输出;
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//首先定义一个数组将nums数组里面的数全部拷贝进去
vector<int> fuzhi;
for(int i=0;i<nums.size();i++){
fuzhi.push_back(nums[i]);
}
//进行排序
sort(fuzhi.begin(),fuzhi.end());
//定义一个返回数组,里面存放最后返回的数值
vector<int> returnnums=twoSumAlogorithm(fuzhi,target);
//寻找返回数组的索引值并存入数组中
vector<int> numindex;
for(int j=0;j<returnnums.size();j++){
int flag=0;
for(int i=0;i<nums.size();i++){
if(returnnums[j]==nums[i] && flag==0){
if((j!=0 && i!=numindex[0]) || j==0){
numindex.push_back(i);
flag=1;
}
}
}
}
if(numindex[0]>numindex[1]){
int t=numindex[0];
numindex[0]=numindex[1];
numindex[1]=t;
}
return numindex;
}
vector<int> twoSumAlogorithm(vector<int>&fuzhi,int target){
int len=fuzhi.size();
vector<int> result;
int i=0;
int j=len-1;
int flag=1;
while(i<j && flag){
if(fuzhi[i]+fuzhi[j]==target){
result.push_back(fuzhi[i]);
result.push_back(fuzhi[j]);
flag=0;
// i++;
//j--;
}
else if(fuzhi[i]+fuzhi[j]>target){
j--;
}
else i++;
}
return result;
}
};
二. 3Sum 题目链接:https://leetcode.com/problems/3sum/
解题思路:a+b+c=0;如果将-c看做target则可以直接调用上面的代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
//定义一个数组存放最后的结果
vector<vector<int>> result;
sort(nums.begin(),nums.end());
//循环调用twosum函数
for(int i=0;i<nums.size();i++){
twoSum(nums,result,i);
while(nums[i]==nums[i+1])
i++;
}
return result;
}
vector<vector<int>> twoSum(vector<int>&nums,vector<vector<int>>&result,int i ){
int target=nums[i];
int start=i+1;
int ends=nums.size()-1;
while(start<ends){
vector <int> linshi;
if(nums[start]+nums[ends]+target==0){
linshi.push_back(target);
linshi.push_back(nums[start]);
linshi.push_back(nums[ends]);
result.push_back(linshi);
start++;
ends--;
while(start<nums.size()&&nums[start]==nums[start-1]) start++;
while(ends>=0 && nums[ends]==nums[ends+1]) ends--;
}
else if(nums[start]+nums[ends]+target>0){
ends--;
}
else start++;
}
return result;
}
};
3Sum Closest题目链接https://leetcode.com/problems/3sum/
解题如下:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result=9999;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
result=SUM(nums,target,result,i);
if (result==target)
return result;
}
return result;
}
int SUM(vector<int>&nums,int target,int result,int i ){
int start=i+1;
int result1=abs(result-target);
//result1存放最后的差值
int end=nums.size()-1;
while(start<end){
//k++;
int ans=nums[i]+nums[start]+nums[end];//-1 -1 1 1 3
//chazhi[k]=ans;
if(ans==target)
return ans;
else if(ans<target){
start++;
}
else end--;
if(result1>abs(ans-target))
{result=ans;
result1=abs(ans-target);
}}
return result;
}
};