leetcode: sum of three numbers

Train of thought: 1. Sort first (from small to large) 2. Outer loop: traverse the array, fix the number nums[i] one at a time, and then make low=i+1,...


Train of thought:
1. Sort first (from small to large)
2. Outer loop: traverse the array, fix the number nums[i] one at a time, and then make low=i+1, high=nums.length-1.
Inner loop: if the sum of the numbers corresponding to the two pointers is less than - nums[i], move the low pointer to the next number different from the current number; similarly, if the sum of the numbers corresponding to the two pointers is greater than - nums[i], move the high pointer to the next number different from the current number; if the sum of the two pointers is equal to - nums[i], then add it to the list , and then move the low pointer to the next different number. This process is repeated until low==high.
3. Avoid repetition: the final requirement of the problem is not to print the same results repeatedly. The solution is to move i to the next number different from the current i after each internal cycle.

public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> answer = new ArrayList<List<Integer>>(); if(nums == null || nums.length < 3){ return answer; } Arrays.sort(nums); for (int i = 0; i < nums.length; ) { int benchmark = nums[i]; int l = i + 1, h = nums.length - 1; while (l < h) { int sum = nums[l] + nums[h]; if (sum < -benchmark) { while (++l < h && nums[l] == nums[l - 1]) ; } else if (sum > -benchmark) { while (l < --h && nums[h] == nums[h + 1]) ; } else { List<Integer> list = new ArrayList<Integer>(); list.add(benchmark); list.add(nums[l]); list.add(nums[h]); answer.add(list); while (++l < h && nums[l] == nums[l - 1]) ; } } while (++i < nums.length && nums[i] == nums[i - 1]) ; } return answer; }

10 November 2019, 13:17 | Views: 7603

Add new comment

For adding a comment, please log in
or create account

0 comments