zoukankan      html  css  js  c++  java
  • 18. 4Sum

    description:

    Given an array nums of n integers and an integer target, are there elements a, b, c, 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]
    ]
    

    my answer:

    感恩

    my answer

    思路和上一道题3sum是一样的,就是多加了个for循环,先后固定两个数,再找另外两个数
    

    大佬的answer:

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int> &nums, int target) {
            set<vector<int>> res;
            sort(nums.begin(), nums.end());
            for (int i = 0; i < int(nums.size() - 3); ++i) {
                for (int j = i + 1; j < int(nums.size() - 2); ++j) {
                    if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                    int left = j + 1, right = nums.size() - 1;
                    while (left < right) {
                        int sum = nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum == target) {
                            vector<int> out{nums[i], nums[j], nums[left], nums[right]};
                            res.insert(out);//这里要用insert, 因为res是个set
                            ++left; --right;
                        } else if (sum < target) ++left;
                        else --right;
                    }
                }
            }
            return vector<vector<int>>(res.begin(), res.end());//因为res是set,所以不能直接返回,要处理一下
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    SpringIOC框架简单实现(注解实现)
    Spring前瞻----Java反射机制
    SpringMVC_前置知识
    SpringAOP_构造注入实现
    SpringAOP_设置注入实现
    SpringIOC-设置注入实现
    IDEA一些常用快捷键
    第一章计算机网络概述
    第二大章--数据链路层思维导图
    第一大章--1.2标准化工作
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10668607.html
Copyright © 2011-2022 走看看