15. 三数之和

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> resultList = new ArrayList<>();
        Arrays.sort(nums);

        for (int first = 0; first < nums.length; first++) {
            int second = first + 1;
            int third = nums.length - 1;

            while (second < third) {
                int temp = nums[second] + nums[third];

                if (temp < -nums[first]) {
                    second++;
                } else if (temp > -nums[first]) {
                    third--;
                } else {
                    int finalFirst = first;
                    int finalSecond = second;
                    int finalThird = third;

                    resultList.add(new ArrayList<Integer>() {
                        private static final long serialVersionUID = 6096004525464010681L;

                        {
                            add(nums[finalFirst]);
                            add(nums[finalSecond]);
                            add(nums[finalThird]);
                        }
                    });

                    while (second < third && nums[second] == nums[second + 1]) {
                        second++;
                    }

                    second++;

                    while (second < third && nums[third] == nums[third - 1]) {
                        third--;
                    }

                    third--;
                }
            }

            while (first < nums.length - 1 && nums[first] == nums[first + 1]) {
                first++;
            }
        }

        return resultList;
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容