Leetcode 18
来源:互联网 发布:ubuntu显示桌面图标 编辑:程序博客网 时间:2024/05/16 18:14
题意
给一个数组和target,要求在数组中找到四个数,使a + b + c + d = target
。
思路
类似于3Sum,排序后枚举其中两个数a和b,然后问题就转化成了2Sum。
时间复杂度
代码
class Solution {private: vector<vector<int>> ans;public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n; i++) { for (int j = n - 1; j > i; j--) { int x = target - nums[i] - nums[j]; int k = i + 1, l = j - 1; while (k < l) { if (nums[k] + nums[l] == x) { vector<int> tv(4); tv[0] = nums[i]; tv[1] = nums[j]; tv[2] = nums[k]; tv[3] = nums[l]; ans.push_back(tv); while (nums[k] == tv[2] && k < l) k++; while (nums[l] == tv[3] && k < l) l--; } else { if (nums[k] + nums[l] < x) k++; else l--; } } while (j > i && nums[j] == nums[j - 1]) j--; } while (i + 1 < n && nums[i] == nums[i + 1]) i++; } return ans; }};
0 0
- leetcode 18
- Leetcode 18
- Leetcode(18)
- LeetCode 18: 4Sum
- [LeetCode] Implement strStr() [18]
- Leetcode【18】:Letter Combinations
- LeetCode 18 Gas Station
- [leetcode 18] 4Sum
- [leetcode] 18 4Sum
- leetcode.18--------------4Sum
- [leetcode]18 Min Stack
- leetcode 18 4Sum
- LeetCode---(18) 4 Sum
- LeetCode 18 - 4Sum
- LeetCode 18: 4Sum
- leetcode 18 -- 4Sum
- Leetcode[18]-4Sum
- leetcode-18 4Sum
- 473. Matchsticks to Square(dfs+回溯) / 416. Partition Equal Subset Sum 动归
- 进程与线程的区别
- ST已发布基于PC端的ST MCU选型工具
- java实现定时任务的三种方法(很好理解)
- 基于扩展C0文法的编译器设计(Part3)
- Leetcode 18
- 八张Gif动图形象地为你介绍 flexbox 是如何工作的
- CocoaPods版本升级
- 频谱仪的RBW带宽和VBW带宽
- 《剑指offer》—2、替换空格
- 复杂链表的复制练习
- JS编写input搜索框,类似下拉搜索框
- 移动端web css适配
- java虚拟机学习随笔