1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import java.util.*; import java.util.stream.IntStream;
public class _15三数之和 {
public List<List<Integer>> threeSum(int[] nums) { int n = nums.length; Arrays.sort(nums); List<List<Integer>> ans = new ArrayList<List<Integer>>(); for (int first = 0; first < n; ++first) { if (first > 0 && nums[first] == nums[first - 1]) { continue; } int third = n - 1; int target = -nums[first]; for (int second = first + 1; second < n; ++second) { if (second > first + 1 && nums[second] == nums[second - 1]) { continue; } while (second < third && nums[second] + nums[third] > target) { --third; } if (second == third) { break; } if (nums[second] + nums[third] == target) { List<Integer> list = new ArrayList<Integer>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); ans.add(list); } } } return ans; }
public List<List<Integer>> threeSum1(int[] nums) { HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } }
List<List<Integer>> res = new ArrayList<>(); if(map.containsKey(0) && map.get(0) >= 3){ List<Integer> list = new ArrayList<>(); list.add(0); list.add(0); list.add(0); res.add(list); }
Integer[] array = map.keySet().toArray(new Integer[0]); for (int i = 0; i < array.length; i++) { map.put(array[i], map.get(array[i]) - 1); HashMap<Integer, Integer> mapPre = (HashMap<Integer, Integer>) map.clone(); for (int j = i+1; j < array.length; j++) { mapPre.put(array[j], map.get(array[j]) - 1); int sub = -array[i] - array[j]; if(mapPre.containsKey(sub) && mapPre.get(sub) > 0){ List<Integer> list = new ArrayList<>(); list.add(array[i]); list.add(array[j]); list.add(sub); res.add(list); } mapPre.remove(array[j]); } map.remove(array[i]); } return res; }
public static void main(String[] args) { _15三数之和 threeSum = new _15三数之和(); System.out.println(threeSum.threeSum(new int[]{-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0})); }
}
|