题解 | #和为S的两个数字#
和为S的两个数字
http://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
class Solution {
public:
//双指针算法
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
if(array.size()==0||array.size()==1)
return res;
int left=0,right=array.size()-1;
while(right>left){
if(array[left]+array[right]==sum){
res.push_back(array[left]);
res.push_back(array[right]);
break;
}
else if(array[left]+array[right]<sum){
left++;
}
else right--;
}
return res;
}
};
public:
//双指针算法
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
if(array.size()==0||array.size()==1)
return res;
int left=0,right=array.size()-1;
while(right>left){
if(array[left]+array[right]==sum){
res.push_back(array[left]);
res.push_back(array[right]);
break;
}
else if(array[left]+array[right]<sum){
left++;
}
else right--;
}
return res;
}
};