多数之和问题(2 -> n)


数组定和问题

本文从两数之和引申到n数之和的算法问题。


提示:以下是本篇文章正文内容,下面案例可供参考

一、两数之和

思想:考察数据结构的使用,map O(1)的查询优势。

问题描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

要点
要点1:map相比数组能更快查到数组值对应的索引
要点2:相加的两数下标不相同

过程
step1:将数组索引放入map,便于查询
step2:遍历数组,对每个数num[ i ], 在map中查找target - num[ i ],得到对应索引

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = {-1, -1};
        for(int i = 0; i < nums.length; i++)
        {
            map.put(nums[i], i);
        }
        for(int i = 0; i < nums.length; i++)
        {
            int temp = target - nums[i];
            if(map.containsKey(temp) &&  i != map.get(temp))
            {
                result[0] = i;
                result[1] = map.get(temp);
                return result;
            }
        }
        return result;
    }
}

优化:若数组有重复元素,改进如下:边查询边建立hash
思路:前半部分建立map,后半部分匹配到前半部分时得到结果

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< nums.length; i++) {
        	//成功匹配:i为后一个元素
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target-nums[i]),i};
            }
            //未成功匹配:使用i建立map
            //case1:i可能与后面的数匹配,i为前一个元素
            //case2:i不会和后面数匹配
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

二、三数之和

1.法一:Map加速查询

问题描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

要点
要点1:算法主要过程的复杂度大于平方级别时,使用排序简化问题
要点2:n个数和问题,target/n 分界

代码如下(示例):

class Solution {
    /*
    想法1:map加速查询
    */
    public List<List<Integer>> threeSum(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        List<List<Integer>> list = new ArrayList<>();
        Set<List<Integer>> set = new LinkedHashSet<>();

        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++)
        {
            if(nums[i] > 0)
                break; //提前停止,无需继续搜索
            
            if( i > 0 && nums[i] == nums[i-1])
                continue; //重复元组只考虑一个
            
            //如下代码为两数之和
            int target = -nums[i];
            for(int j = i + 1; j < nums.length; j++)
            {
                if(map.containsKey(target - nums[j]))
                    set.add(Arrays.asList(nums[i], nums[map.get(target - nums[j])], nums[j]));
                else
                    map.put(nums[j], j);
            }  
            map.clear();  
        }
         for(List<Integer> list0 : set)
            list.add(list0);
        return list;
    }
}

2.法二:排序+双指针

注:该方法也是一种常用思路,移动 左指针 和 右指针 调节结果的大小
排序+双指针:使用L,R调整当前值以达到目标值。

方法思路
要点1:三个数中必有一个小于0,对每个小于0的数:进行两数之和问题
要点2:当前和小于target,L++;当前和大于target,R–。

代码如下(示例):

class Solution {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList();
        int len = nums.length;
        if(nums == null || len < 3) return ans;
        Arrays.sort(nums); 
        
        for (int i = 0; i < len ; i++) {
            if(nums[i] > 0) 
            	break; //提前结束
            if(i > 0 && nums[i] == nums[i-1]) 
            	continue; // 去重
            
            //设置左右指针
            int L = i+1;
            int R = len-1;
            while(L < R){
                int sum = nums[i] + nums[L] + nums[R];
                if(sum == 0){
                    ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while (L<R && nums[L] == nums[L+1]) L++; // 去重
                    while (L<R && nums[R] == nums[R-1]) R--; // 去重
                    L++;
                    R--;
                }
                else if (sum < 0) 
                	L++;
                else if (sum > 0) 
                	R--;
            }
        }        
        return ans;
    }
}

n个数之和

原理同三数之和:排序+双指针

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> quadruplets = new ArrayList<List<Integer>>();
        if (nums == null || nums.length < 4) {
            return quadruplets;
        }
        Arrays.sort(nums);
        int length = nums.length;
        for (int i = 0; i < length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                break;
            }
            if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
                continue;
            }
            for (int j = i + 1; j < length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
                    break;
                }
                if (nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
                    continue;
                }
                int left = j + 1, right = length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        left++;
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }
        return quadruplets;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值