题解 | #三数之和#

三数之和

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

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (num == null || num.length < 3) {
            return res;
        }
        int n = num.length;
        Arrays.sort(num);
        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && num[i] == num[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = n - 1;
            while (left < right) {
                int sum = num[i] + num[left] + num[right];
                if (sum == 0) {
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(num[i]);
                    list.add(num[left]);
                    list.add(num[right]);
                    res.add(list);
                    int tmp = num[left];
                    while (left < right && num[left] == tmp) {
                        left++;
                    }
                    tmp = num[right];
                    while (left < right && num[right] == tmp) {
                        right--;
                    }
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }
}

全部评论

相关推荐

FieldMatching:看成了猪头顾问,不好意思
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务