首页 > 技术文章 > 3. 四数之和(数组、Hashset)(18题)

shizhe99 2020-12-08 10:35 原文

 

 

思路及算法:

该题与第15题的“三数之和”相似,四数之和为一个目标值,就是三数之和为目标值减去第四个数,然后按照15题的基础上稍加修改就成功了。因为不能重复,所以,首先进行了一遍排序;其次,在枚举的时候判断了本次的第四个数的值是否与上一次的相同;再次,在枚举的时候判断了本次的第三个数的值是否与上一次的相同,不过注意的是本次判断是否相同是i与n+1比较的,以避免了nums[n] = nums [i]的情况;同时,在寻找hashset时,判断当前的num[ j ]是否重复;最后,在枚举完一个第三个数之后,清空hashset,因为hashset的目的是判断最后2数之和的值,使用本题依旧在枚举完第三个数之后清空hashset。本题的答题思想与第15题类似,难度在于不可重复

代码:

Java:
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //从小到大排序
        Arrays.sort(nums);
        //建立返回的list
        List<List<Integer>> result = new LinkedList<>();
        //定义hashset
        Set<Integer> hashset = new HashSet<>();
        for(int n = 0;n < nums.length - 3 ; n++){
            // 需要和上一次枚举的数不相同
            if ( n > 0 && nums[ n ] == nums[ n - 1]) {
                    continue;
            }
            //target_3是剩下3个数之和
            int target_3 = target - nums[ n ];
            for(int i = n+1 ;i < nums.length - 2 ; i++){
                // 需要和上一次枚举的数不相同,注意这里是i与n+1比较
                if ( i > n+1 && nums[ i ] == nums[ i - 1]) {
                    continue;
                }
                //target_2是剩下2个数之和
                int target_2 = target_3 - nums[i];
                //pre为上一个符合条件的num[j],定义为Integer.MAX_VALUE是为了避免与输入冲突
                int pre = Integer.MAX_VALUE;
                for(int j = i + 1; j < nums.length ; j++){
                    //hashset中需要寻找的值
                    int other = target_2 - nums[j];
                    if (hashset.contains(other)) {
                        //判断当前的num[j]是否重复
                        if(pre == nums[j]){
                            continue;
                        }
                        result.add(new LinkedList<>(Arrays.asList(nums[n],nums[i], other , nums[j] )));
                        pre = nums[j];
                    }
                    //未找到对应的other值,就将当前nums[j]插入hashset
                    hashset.add(nums[j]);
                }
                //清空hash表
                hashset.clear();
            }
        }
        return result;
    }
}

复杂度分析:

 

 提交结果:

 

推荐阅读