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

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

    Note:

    The solution set must not contain duplicate quadruplets.

    Example:

    Given array nums = [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]
    ]
     1 class Solution {
     2 public:
     3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
     4         int size = nums.size();
     5         sort(nums.begin(), nums.end());
     6         vector<vector<int>> ans;
     7         for (int i = 0; i < size; i++) {
     8             if (i > 0 && nums[i] == nums[i - 1])continue;
     9             for (int j = i + 1; j < size - 2; j++) {
    10                 if (j > i + 1 && nums[j] == nums[j - 1])continue;
    11                 int p = j + 1, q = size - 1;
    12                 int res = target - nums[i] - nums[j];
    13                 while (p < q) {
    14                     int tmp = nums[p] + nums[q];
    15                     if (tmp < res)p++;
    16                     else if (tmp == res) {
    17                         vector<int> tt;
    18                         tt.push_back(nums[i]);
    19                         tt.push_back(nums[j]);
    20                         tt.push_back(nums[p]);
    21                         tt.push_back(nums[q]);
    22                         ans.push_back(tt);
    23                         while (nums[p + 1] == nums[p])p++;
    24                         while (nums[q - 1] == nums[q])q--;
    25                         p++, q--;
    26                     }
    27                     else q--;
    28                 }
    29             }
    30         }
    31         return ans;
    32     }
    33 };
    View Code

    跟3sum基本相同

    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    jQuery插件 -- Form表单插件jquery.form.js
    Ajax发送GET、POST请求和响应XML数据案例
    Ajax知识点复习
    Tomcat配置连接池的java实现
    dbcp数据库连接池的java实现
    C3P0数据库连接池的java实现
    推荐几款基于Bootstrap的响应式后台管理模板
    Java复习第四天
    Java复习第三天
    Java复习第二天
  • 原文地址:https://www.cnblogs.com/yalphait/p/10333324.html
Copyright © 2011-2022 走看看