• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
18. 4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

注意:

加入剪枝条件:

if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)
  break;
if(nums[i]+nums[j]+nums[l-2]+nums[l-1]<target)
  continue;
加之前120ms,之后20ms。
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int l = nums.size(), sum, left, right, i, j;
        vector<vector<int>> ans;
        if (l<4)
            return ans;
        sort(nums.begin(), nums.end());
        for (i = 0; i<l - 3; i++)
        {
            if(i && nums[i] == nums[i-1])
                continue;
            for (j = i + 1; j<l - 2; j++)
            {
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)
                    break;
                if(nums[i]+nums[j]+nums[l-2]+nums[l-1]<target)
                    continue;
                if (j>i + 1 && nums[j] == nums[j - 1])
                    continue;
                sum = nums[i] + nums[j];
                left = j + 1;
                right = l - 1;
                while (left < right)
                {
                    if (sum + nums[left] + nums[right] == target)
                        ans.push_back({ nums[i], nums[j], nums[left++], nums[right--] });
                    else if (sum + nums[left] + nums[right] < target)
                        left++;
                    else
                        right--;
                    while (left>j+1 && nums[left] == nums[left - 1])
                        left++;
                    while(right<l-1 && nums[right] == nums[right + 1])
                        right--;
                }
            }
        }
        return ans;
    }
};

 

 
posted on 2016-02-28 11:20  ArgenBarbie  阅读(128)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3