Prompt
Three Number Sum
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should nd all triplets in the array that sum up to the target sum and return a twodimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold.
If no three numbers sum up to the target sum, the function should return an empty array.
Sample Input
array = [12, 3, 1, 2, -6, 5, -8, 6]
targetSum = 0
Sample Output
[[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
Solution 1
import java.util.*;
class Program {
//O(n^2) time | O(n) space
public static List<Integer[]> threeNumberSum(int[] array, int targetSum) {//A
Arrays.sort(array);
List<Integer[]> triplets = new ArrayList<Integer[]>();//B
for(int currentNum = 0; currentNum < array.length - 2; currentNum ++){
int left = currentNum + 1;
int right = array.length -1;
while(left < right) {
Integer[] newTriplet = {array[currentNum], array[left], array[right]};
triplets.add(newTriplet);
if (currentSum == targetSum) {
triplets.add(new Integer[]{array[currentNum], array[left], array[right]});//C
left ++;
right --;
} else if (currentSum > targetSum){
right --;
} else if (currentSum < targetSum){
left ++;
}
}
}
return triplets;
}
}
# 1A
看清楚题目的返回值
# 1B
#1C
triplets.add(new Integer[]{array[currentNum], array[left], array[right]});
- new Integer [] 和new int []