题解 | #三数之和#

三数之和

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

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        Map<ArrayList, Integer> map = new HashMap<>();
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {
            boolean flagJ = false;
            for (int j = i + 1; j < num.length - 1; j++) {
                boolean flagK = false;
                for (int k = j + 1; k < num.length; k++) {
                    if (num[i] + num[j] + num[k] == 0) {
                        flagK = true;
                        flagJ = true;
                        ArrayList<Integer> temp = new ArrayList<>();
                        temp.add(num[i]);
                        temp.add(num[j]);
                        temp.add(num[k]);
                        if (!map.containsKey(temp)) {
                            map.put(temp, 0);
                            ans.add(temp);
                        }
                    } else if (num[i] + num[j] + num[k] > 0) {
                        break;
                    } else {
                        flagK = true;
                        flagJ = true;
                    }
                }
                if (!flagK) {
                    break;
                }
            }
            if (!flagJ) {
                break;
            }
        }
        return ans;
    }
}

全部评论

相关推荐

自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务