题解 | #三数之和#

三数之和

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

暴力法解题! ArrayList的contains去重!

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param num int整型一维数组
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> threeSum (int[] num) {
        int len = num.length;
        // Set<ArrayList<Integer>> set = new HashSet<>();
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        for (int i = 0; i < len - 2; i++) {
            for (int j = i + 1; j < len - 1; j++) {
                for (int w = j + 1; w < len; w++) {
                    if (num[i] + num[j] + num[w] == 0) {
                        ArrayList<Integer> tmp = new ArrayList<>();
                        tmp.add(num[i]);
                        tmp.add(num[j]);
                        tmp.add(num[w]);
                        Collections.sort(tmp);
                        if (!res.contains(tmp)) {
                            res.add(tmp);
                        }
                    }
                }
            }
        }
        return res;
    }
}

全部评论

相关推荐

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