美文网首页
[leetcode] 259.3sum smaller

[leetcode] 259.3sum smaller

作者: 叶孤陈 | 来源:发表于2017-06-05 21:58 被阅读0次

    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<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;
        }
    };
    
    

    相关文章

      网友评论

          本文标题:[leetcode] 259.3sum smaller

          本文链接:https://www.haomeiwen.com/subject/laywfxtx.html