3 Sum

来源:互联网 发布:淘宝兼职红包单 编辑:程序博客网 时间:2024/04/27 01:17
public class Solution {    public List<List<Integer>> threeSum(int[] nums) {        if (nums == null) {throw new IllegalArgumentException("haha");}List<List<Integer>> res = new LinkedList<>();if (nums.length < 3) {return res;}Arrays.sort(nums);for (int i = 0; i < nums.length - 2; i++) {if (i > 0 && nums[i] == nums[i - 1]) {continue;}int l = i + 1;int r = nums.length - 1;while (l < r) {int sum = nums[i] + nums[l] + nums[r];if (sum == 0) {List<Integer> list = new LinkedList<>();list.add(nums[i]);list.add(nums[l]);list.add(nums[r]);res.add(list);l++;r--;while (l < nums.length && nums[l] == nums[l - 1]) {l++;}while (r >= 0 && nums[r] == nums[r + 1]) {r--;}} else if (sum > 0) {r--;} else {l++;}}}return res;    }}

0 0
原创粉丝点击