标签:
和3sum 相似 ,比3sum多一层循环。
public class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] nums, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (nums == null || nums.length < 3) { return res; } Arrays.sort(nums); for (int i = 0; i< nums.length - 3; i++) { if (i != 0 && nums[i] == nums[i-1]) { continue; } for (int j = i+1; j<nums.length - 2; j++) { if (j != i+1 && nums[j] == nums[j-1]) { continue; } int left = j+1; int right = nums.length - 1; while (left < right) { int sum = nums[left] + nums[right] + nums[i] + nums[j]; if (sum < target) { left++; } else if (sum > target) { right--; } else { ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.add(nums[i]); tmp.add(nums[j]); tmp.add(nums[left]); tmp.add(nums[right]); res.add(tmp); left++; right--; while (left < right && nums[left] == nums[left - 1]) { left++; } while (left < right && nums[right] == nums[right +1]) { right--; } } } } } return res; } }
标签:
原文地址:http://www.cnblogs.com/77rousongpai/p/4522588.html