如题:
思路:
1. 先将数组排序
2.循环遍历数组元素,采用双指针法,如:当前元素下标为 i ,则低指针为 i+1, 高指针为 arr.length - 1 .
3. 如果三下标所对应元素的和 大于0,则 高指针减小一,如果和小于0则低指针加一, 否则 则等于 0。
4. 如果等于0,再判断有没有重复元素。
代码:
public class AddThreeToZero {
//=================================排序开始==========================
public static void quickSort(int[] nums, int low, int high){ //快速排序
int pivor = getPivor(low, high,nums);
if(low < high){
quickSort(nums, low, pivor - 1);
quickSort(nums, pivor + 1, high);
}
}
public static int getPivor(int low, int high, int[] arr){
int pivorKey = arr[low];
while(low < high){
while(low < high && arr[high] >= pivorKey)
high --;
swap(low, high, arr);
while(low < high && arr[low] <= pivorKey)
low ++;
swap(low, high, arr);
}
return low;
}
public static void swap(int i, int j, int[] arr){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//==================================排序结束===============================
public static List<List<Integer>> threeSum(int[] nums) throws Exception {
HashMap<Integer, Integer> map = new HashMap<>();
quickSort(nums, 0, nums.length-1);
System.out.println("after sort: " + Arrays.toString(nums));
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums[0] > 0 || nums.length < 3)
throw new Exception("noooooo");
for(int i = 0; i < nums.length; i ++){
int left = i + 1, right = nums.length - 1;
while(left < right){
if(nums[i] + nums[left] + nums[right] > 0){
right --;
}else if(nums[i] + nums[left] + nums[right] < 0){
left ++;
}else{
System.out.println("left=====> " + left + ", right=====> " + right);
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
if(res.contains(list)){
//already exists, do nothing
}else{
res.add(list);
}
break;
}
}
}
return res;
}
public static void main(String[] args) throws Exception {
int[] arr = {-1, 0, 1, 2, -1, -4};
System.out.println(threeSum(arr).toString());
}
}
运行结果: