三个数的和
别人的代码,总是那么优美。
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.List; 4 5 class Solution { 6 public static List<List<Integer>> threeSum(int[] nums) { 7 List<List<Integer>> result = new ArrayList<>(); 8 int len = nums.length; 9 if (nums == null || len < 3) 10 return result; 11 Arrays.sort(nums); 12 for (int i = 0; i < len; i++) { 13 if (nums[i] > 0) 14 break; 15 if (i > 0 && nums[i] == nums[i - 1]) // 去重 16 continue; 17 // 双指针 18 int L = i + 1; 19 int R = len - 1; 20 while (L < R) { 21 int sum = nums[i] + nums[L] + nums[R]; 22 if (sum == 0) { 23 result.add(Arrays.asList(nums[i], nums[L], nums[R])); 24 while (L < R && nums[L] == nums[L + 1]) 25 L++; 26 while (L < R && nums[R] == nums[R - 1]) 27 R--; 28 L++; 29 R--; 30 } else if (sum < 0) { 31 L++; 32 } else if (sum > 0) { 33 R--; 34 } 35 } 36 } 37 return result; 38 } 39 } 40 41 public class ThreeSum { 42 43 public static void main(String[] args) { 44 Solution s = new Solution(); 45 int nums[] = {-1,0,1,2,-4}; 46 System.out.println(s.threeSum(nums)); 47 } 48 49 }