Leetcode-15: 3Sum
来源:互联网 发布:b2c商城网站源码下载 编辑:程序博客网 时间:2024/06/08 05:37
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]]
思路:
1. 朴素遍历所有的3元素子集,复杂度:O(n^3),然后筛除重复元素,由于solution需要升序排列,所以可以先对数组S进行排序。
2. 对朴素遍历法进行精简:1) 可转化为2Sum问题,即解决n个target为-num[i]的2Sum问题,复杂度降至O(n^2)。2)重复元素的筛除:可通过set去除重复元素,也可以在遍历的时候跳过元素。
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new LinkedList<>(); Arrays.sort(nums); for (int targetInd = 0; targetInd < nums.length - 2; ++targetInd) { if (nums[targetInd] > 0) break; if (targetInd > 0 && nums[targetInd] == nums[targetInd - 1]) continue; int target = -nums[targetInd]; int head = targetInd + 1, tail = nums.length - 1; while (head < tail) { if (target == nums[head] + nums[tail]) { res.add(Arrays.asList(nums[targetInd], nums[head], nums[tail])); while (head < tail && nums[head + 1] == nums[head]) ++head; while (head < tail && nums[tail - 1] == nums[tail]) --tail; ++head; --tail; } else if (target > nums[head] + nums[tail]) ++head; else --tail; } } return res; }}
阅读全文
0 0
- Leetcode 15 3Sum
- LeetCode 15: 3Sum
- leetcode 15 3Sum
- [leetcode 15] 3Sum
- Leetcode【15】:3Sum
- [leetcode 15] 3Sum
- [Leetcode] 15 - 3Sum
- leetcode.15-----------3Sum
- leetcode 15 3Sum
- leetcode-15 3Sum
- 3Sum - LeetCode 15
- Leetcode #15 3 Sum
- LeetCode---(15) 3 sum
- LeetCode 15 - 3Sum
- leetcode-15 3sum
- leetcode 15 -- 3Sum
- Leetcode[15]-3Sum
- LeetCode 15: 3 Sum
- 设计模式
- 安卓-天气预报(逐渐整理)
- epel安装
- 三(8)、JSP九大内置对象——page
- 【JavaSE笔记】IO(三)IO流_字节流
- Leetcode-15: 3Sum
- 20170810(初学git)
- react native 在设备在运行时的问题
- Groovy学习记录-------Groovy安装/配置
- ansible安装
- EasyUI 学习与总结
- Elasticsearch系列(二)----Elasticsearch 基本使用
- 排序算法汇总
- apache的基本配置