18. 4Sum(Leetcode每日一題-2020.10.05)
Problem
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.
Notice that the solution set must not contain duplicate quadruplets.
Constraints:
- 0 <= nums.length <= 200
- -109 <= nums[i] <= 109
- -109 <= target <= 109
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/4sum
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
Example1
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example2
Input: nums = [], target = 0
Output: []
Solution
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i ++ )
{
if (i && nums[i] == nums[i - 1])
continue;
for (int j = i + 1; j < nums.size(); j ++ )
{
if (j > i + 1 && nums[j] == nums[j - 1])
continue;
for (int k = j + 1, u = nums.size() - 1; k < u; k ++ )
{
if (k > j + 1 && nums[k] == nums[k - 1])
continue;
while (u - 1 > k && nums[i] + nums[j] + nums[k] + nums[u - 1] >= target)
u -- ;
if (nums[i] + nums[j] + nums[k] + nums[u] == target)
{
res.push_back({nums[i], nums[j], nums[k], nums[u]});
}
}
}
}
return res;
}
};
相關文章
- 10.5 每日一題 18. 四數之和每日一題
- 【10月打卡~Leetcode每日一題】18. 四數之和(難度:中等)LeetCode每日一題
- leetcode每日一題LeetCode每日一題
- Leetcode每日一題(1)LeetCode每日一題
- Leetcode 18 4SumLeetCode
- LeetCode 2024/6 每日一題 合集LeetCode每日一題
- LeetCode 每日一題「判定字元是否唯一」LeetCode每日一題字元
- LeetCode每日一題: 找不同(No.389)LeetCode每日一題
- LeetCode每日一題: 移除元素(No.27)LeetCode每日一題
- 【Leetcode】18. 4Sum 給定陣列中的4個元素之和等於給定值的所有組合LeetCode陣列
- 75. Sort Colors(Leetcode每日一題-2020.10.07)LeetCode每日一題
- LeetCode每日一題: 排列硬幣(No.441)LeetCode每日一題
- LeetCode每日一題: 各位相加(No.258)LeetCode每日一題
- 【LeetCode】每日一題164. 最大間距LeetCode每日一題
- LeetCode每日一題: 移動零(No.283)LeetCode每日一題
- LeetCode每日一題:迴文數(No.9)LeetCode每日一題
- LeetCode每日一題:兩數之和(No.1)LeetCode每日一題
- LeetCode每日一題:自除數(No.728)LeetCode每日一題
- LeetCode每日一題:Nim遊戲(No.292)LeetCode每日一題遊戲
- LeetCode每日一題:求眾數(No.169)LeetCode每日一題
- LeetCode每日一題:爬樓梯(No.70)LeetCode每日一題
- Leetcode每日一題:面試題16.19.水域大小LeetCode每日一題面試題
- leetcode每日一題刷題記錄(10.26-10.30)LeetCode每日一題
- 【js】Leetcode每日一題-葉子相似的樹JSLeetCode每日一題
- 【leetcode】(每日一題 771 寶石與石頭)LeetCode每日一題
- LeetCode每日一題 (32)1. 兩數之和LeetCode每日一題
- 【每日一題-leetcode】416. 分割等和子集每日一題LeetCode
- LeetCode每日一題: 旋轉陣列(No.189)LeetCode每日一題陣列
- LeetCode每日一題: 猜數字大小(No.374)LeetCode每日一題
- LeetCode每日一題: 搜尋插入位置(No.35)LeetCode每日一題
- LeetCode每日一題: 轉置矩陣(No.867)LeetCode每日一題矩陣
- 135. Candy(Leetcode每日一題-2020.12.24)--抄答案LeetCode每日一題
- LeetCode:每日一題:27. 移除元素 ——————簡單LeetCode每日一題
- 2020年12月4日leetcode每日一題LeetCode每日一題
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- LeetCode每日一題:整數反轉(No.7)LeetCode每日一題
- LeetCode每日一題: 路徑總和(No.112)LeetCode每日一題
- LeetCode每日一題:最長公共字首(No.14)LeetCode每日一題