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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解題思路
本題是3 sum的變種題隐绵,求三個(gè)數(shù)之和小于一個(gè)目標(biāo)值的組數(shù)膏秫,和3 sum一樣的思路见妒,將3個(gè)數(shù)之和求出與目標(biāo)值比較腾务,如果小哮缺,結(jié)果加一吴旋。
代碼如下:
class Solution{
public:
int threeSumSmaller(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int res = 0;
int number = nums.size();
for(int i = 0; i < number - 2; ++i)
{
int l = i + 1 , r= number - 1;
while(l < r)
{
if(nums[i] + nums[l] + nums[r] < target)
{
res++;
l++;
} else{
r--;
}
}
}
return res;
}
};