zoukankan      html  css  js  c++  java
  • [LeetCode]4Sum

    4Sum

    Given an array S of n integers, are there elements abc, 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.
        For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
    
        A solution set is:
        (-1,  0, 0, 1)
        (-2, -1, 1, 2)
        (-2,  0, 0, 2)

    四个的时候如果用3Sum的方法会超时。这时候应该想到二分搜索。确定两个值,然后二分搜索剩下的两个值。3Sum也可以用二分查找的方法,确定一个值,然后二分查找。
    最后可以用set做一个去重的工作。
     1 class Solution {
     2 public:
     3     vector<vector<int> > fourSum(vector<int> &nums, int target) {
     4         vector<vector<int>> result;
     5         if(nums.size()<4)return result;
     6         sort(nums.begin(),nums.end());
     7         set<vector<int>> tmpres;
     8         for(int i = 0; i < nums.size(); i++)
     9         {
    10             for(int j = i+1; j < nums.size(); j++)
    11             {
    12                 int begin = j+1;
    13                 int end = nums.size()-1;
    14                 while(begin < end)
    15                 {
    16                     int sum = nums[i]+ nums[j] + nums[begin] + nums[end];
    17                     if(sum == target)
    18                     {
    19                         vector<int> tmp;
    20                         tmp.push_back(nums[i]);
    21                         tmp.push_back(nums[j]);
    22                         tmp.push_back(nums[begin]);
    23                         tmp.push_back(nums[end]);
    24                         tmpres.insert(tmp);
    25                         begin++;
    26                         end--;
    27                     }else if(sum<target)
    28                         begin++;
    29                     else
    30                         end--;
    31                 }
    32             }
    33         }
    34         set<vector<int>>::iterator it = tmpres.begin();
    35         for(; it != tmpres.end(); it++)
    36             result.push_back(*it);
    37         return result;
    38     }
    39 };
     
  • 相关阅读:
    使用require.context引入模块
    npm link的使用
    mysql 链接远程数据库
    微信错误:errcode=45015, errmsg=response out of time limit or subscription is canceled
    微信公众号发送模板消息
    VS CODE 开发php实现断点调试
    uni 蓝牙 安卓 监听不到返回数据 不可写入
    vue3.0 兄弟组件传值
    二叉查找树的实现和删除
    模块二:ES新特性与TypeScript、JS性能优化
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4754573.html
Copyright © 2011-2022 走看看