leetcode 日记 4sum java
整体思路同之前的一样,依然采取降低维度的方式进行
public List<List<Integer>> solution(int nums[], int target) { List<List<Integer>> result = new ArrayList<>(); if((nums.length<4)||(nums==null)) { return result; } Arrays.sort(nums); if ((4*nums[0]>target)||(4*nums[nums.length-1]<target)) { return result; }//上面两个队特例的快速结束一定要加 int N = nums.length; for (int i = 0; i < N; i++) { int[] temnum = new int[N - 1]; System.arraycopy(nums, 0, temnum, 0, i); System.arraycopy(nums, i + 1, temnum, i, N - i - 1); result = threeSum(temnum, target - nums[i], nums[i], result); } return result; } public List<List<Integer>> threeSum(int[] nums, int target, int num,List<List<Integer>> result) { int sum; for (int i = 0; i < nums.length - 2; i++) { int start = i + 1, end = nums.length - 1; while (start < end) { sum = nums[i] + nums[start] + nums[end]; if (sum < target) { start++; continue; } if (sum > target) { end--; continue; } //下面的部分为对每一结果内部进行进行排序,这样在去重时方便 if (sum == target) { List<Integer> list = new ArrayList<>(); if(num<nums[i]) list.add(num); list.add(nums[i]); if(num>=nums[i] && num<nums[start]) list.add(num); list.add(nums[start]); if ( num>=nums[start] &&num<nums[end]) list.add(num); list.add(nums[end]); if (num>=nums[end]) list.add(num); start++; end--; if (result.contains(list)) continue; result.add(list); } } } return result; }
整体速度在leetcode上大概为50%