题解 | #数组中相加和为0的三元组# | JAVA | 利用2数之和解题

数组中相加和为0的三元组

http://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

简单易懂, 不喜欢写文字解题了, 说一下大致思路

  1. 要先会2数之和
  2. 其中的几个while条件是用来跳循环的
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
        if (num.length == 0) {
            return arr;
        }
        Arrays.sort(num);
        for (int i = 0; i < num.length; i++) {
            ArrayList<ArrayList<Integer>> result = twoSum(num,i +1 , 0 - num[i]);
            if (result.size() > 0) {
                for (ArrayList<Integer> integers : result) {
                    arr.add(new ArrayList<>(Arrays.asList( num[i] ,integers.get(0), integers.get(1))));
                }
            }
            while (i < num.length -1 && num[i] == num[i + 1]) {
                i++;
            }
        }
        return arr;
    }


    public ArrayList<ArrayList<Integer>> twoSum(int[] num,int i , int target) {
        int left = i, right = num.length -1;
        ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
        while (left < right) {
            ArrayList<Integer> temp = new ArrayList<>();
            int result = target - (num[left] + num[right]);
            int leftValue = num[left];
            int rightValue = num[right];
            if (result == 0) {
                temp.add(leftValue);
                temp.add(rightValue);
                arr.add(temp);
                while (left < right && leftValue == num[left] ){
                    left++;
                }
                while (left < right && rightValue == num[right]){
                    right--;
                }
            } else if (result < 0) {
                while (left < right && rightValue == num[right]){
                    right--;
                }
            } else if(result > 0) {
                while (left < right && leftValue == num[left] ){
                    left++;
                }
            }
        }
        return arr;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务