Leetcode_0015_3Sum 3数之和

87 阅读1分钟
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Leetcode_0015_3Sum {

   public static List<List<Integer>> threeSum(int[] nums) {
      Arrays.sort(nums);
      List<List<Integer>> ans = new ArrayList<>();
      // 第一个数选了i位置的数
      for (int i = 0; i < nums.length - 2; i++) {
         if (i == 0 || nums[i - 1] != nums[i]) {
            List<List<Integer>> nexts = twoSum(nums, i + 1, -nums[i]);
            for (List<Integer> cur : nexts) {
               cur.add(0, nums[i]);
               ans.add(cur);
            }
         }
      }
      return ans;
   }

   // nums已经有序了
   // nums[begin......]范围上,找到累加和为target的所有二元组
   public static List<List<Integer>> twoSum(int[] nums, int begin, int target) {
      int L = begin;
      int R = nums.length - 1;
      List<List<Integer>> ans = new ArrayList<>();
      while (L < R) {
         if (nums[L] + nums[R] > target) {
            R--;
         } else if (nums[L] + nums[R] < target) {
            L++;
         } else {
            if (L == begin || nums[L - 1] != nums[L]) {
               List<Integer> cur = new ArrayList<>();
               cur.add(nums[L]);
               cur.add(nums[R]);
               ans.add(cur);
            }
            L++;
         }
      }
      return ans;
   }
}