[Leetcode] Two Sum, 3Sum,4Sum,4SumII,3Sum Closet

Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1.解题思路

题目要求两个数和等于target,返回其index.题目说明不会有重复情况,所以我们一旦发现符合情况的,就可以直接结束循环并返回。
利用HashMap<nums[i],i>,边遍历存储,边寻找。当给定一个数n,只要看target-n是否在map中即可,如果存在,则取出其value - 即该数的下标。

2.代码

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res=new int[2];
        if(nums.length==0) return res;
        HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            int diff=target-nums[i];
            if(hm.containsKey(diff)){
                res[0]=i;
                res[1]=hm.get(diff);
                return res;
            }
            hm.put(nums[i],i);
        }
        return res;
    }
}

3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

1.解题思路

本题要求三个数的和为0,其实就是固定一个数n之后,找两个数和为0-n,所以就转化为求两个数的和,那我们很容易想到使用二分法。
注意点:本题需要排除重复值,
1)固定的数下标为i,则要从i+1开始寻找后两个数;
2)如果数组中包含重复的数,则为了保证结果不出现重复,我们每次遇到重复的数需要跳过。

2.代码

public class Solution {
    List<List<Integer>> res =new ArrayList<List<Integer>>();
    public List<List<Integer>> threeSum(int[] nums) {
      
       Arrays.sort(nums);
      
       for(int i=0;i<nums.length-2;i++){
           if(i>0&&nums[i]==nums[i-1]) continue; //避免重复
           twoSum(0-nums[i],nums,i+1,nums.length-1);
       }
       return res;
    }
    private void twoSum(int target,int[] nums, int start,int end){
        
        int i=start,j=end;
        while(i<j){
            List<Integer> subres=new ArrayList<Integer>();
            int sum=nums[i]+nums[j];
            if(sum==target){
                subres.add(0-target);
                subres.add(nums[i]);
                subres.add(nums[j]);
                res.add(subres);
                
               do {
                    i++;
                }while(i < end && nums[i] == nums[i-1]);
                do {
                    j--;
                } while(j >= 0 && nums[j] == nums[j+1]);
            }
            else if(sum<target) i++;
            else j--;
        }
    }
}

4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

1.解题思路

4Sum,就是在3Sum基础上再嵌套一层,注意点也是要避免重复。

2.代码

public class Solution {
    ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;i++){
            if(i>0&&nums[i]==nums[i-1]) continue;
              res.addAll(threesum(target-nums[i],nums,i+1));
        }
        return res;
    }
    private List<List<Integer>> threesum(int target,int[] nums,int start){
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        int first=start-1;
        for(int i=start;i<nums.length-1;i++){
            if(i>start&&nums[i]==nums[i-1]) continue;
            res.addAll(twosum(target-nums[i],nums,i+1,first));
        }
        return res;
    }
    private List<List<Integer>> twosum(int target,int[] nums,int start,int first){
        List<List<Integer>> res =new ArrayList<List<Integer>>();
        int second=start-1;
        int i=start;
        int j=nums.length-1;
        while(i<j){
            List<Integer> subres =new ArrayList<Integer>();
            int sum=nums[i]+nums[j];
            if(sum==target){
                subres.add(nums[first]);
                subres.add(nums[second]);
                subres.add(nums[i]);
                subres.add(nums[j]);
                res.add(subres);
                i++;
                while(i<nums.length&&nums[i]==nums[i-1]){
                    i++;
                }
                j--;
                while(j>=0&&nums[j]==nums[j+1]){
                    j--;
                }
            }
            else if(sum>target) j--;
            else i++;
            
        }
        return res;
    }
}

3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

1.解题思路

与3Sum相似,只不过本次是要寻找最接近target的3个数之和,我们需要维护minDiff和closetSum两个变量。
但是本题题目说明不许考虑重复。 特殊情况就是sum正好等于target,那肯定是最接近的情况,直接返回即可。

2.代码

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length==0) return 0;
        int minDiff=Integer.MAX_VALUE;
        int closet=0;
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            int left=i+1;
            int right=nums.length-1;
            while(left<right){
                int sum=nums[i]+nums[left]+nums[right];
                int diff=Math.abs(sum-target);
                if(diff<minDiff){
                    minDiff=diff;
                    closet=sum;
                }
                if(sum<target){
                    left++;
                }
                else if(sum>target){
                    right--;
                }
                else return sum;
            }
        }
        return closet;
    }
}

4Sum II

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

1.解题思路

本题从1个数组扩展到了4个数组,求的是有多少组4数之和等于target的,我们把问题分为两个数一组,假设当前两个数A[i]+B[j],那我们其实就是要在C和D中求是否存在和为0-A[i]-B[j],如果存在则返回存在的个数。想到用HashMap,存储<sum,count>.

2.代码

public class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        if(A.length==0||B.length==0||C.length==0||D.length==0) return 0;
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        int count=0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<B.length;j++){
                int sum=A[i]+B[j];
                if(map.containsKey(sum)){
                    map.put(sum,map.get(sum)+1);
                }
                else  map.put(sum,1);
            }
        }
        for(int i=0;i<C.length;i++){
            for(int j=0;j<D.length;j++){
                int sum=0-C[i]-D[j];
                if(map.containsKey(sum)){
                    count+=map.get(sum);
                }
            }
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值