[leetcode] 259.3sum smaller

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的变种题,求三个数之和小于一个目标值的组数,和3 sum一样的思路,将3个数之和求出与目标值比较,如果小,结果加一。
代码如下:

class Solution{
public:
    int threeSumSmaller(vector& 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;
    }
};

你可能感兴趣的:([leetcode] 259.3sum smaller)