LeetCode: 关于Sum的题目合集

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

用HashTable来存补数(target - number)和index的映射关系。注意skip掉Index相同的数。O(n) runtime, O(n) space

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] res = new int[2];
        for(int i = 0; i < numbers.length; i++){
            int num = numbers[i];
            int key = target - num;
            if(!map.containsKey(key)){
                map.put(key, i);
            }
        }
        for(int i = 0; i < numbers.length; i++){
            int num = numbers[i];
            if(map.containsKey(num)){
                int index1 = i;
                int index2 = map.get(num);
                if(index1 == index2){
                    continue;
                }
                res[0] = index1 < index2 ? index1 + 1 : index2 + 1;
                res[1] = index1 < index2 ? index2 + 1 : index1 + 1;
                return res;
            }
        }
        return null;
    }
}

这里其实可以写得更简练。其实可以只扫一遍不用预处理,因为如果存在two sum那么这两个都基于target互为补数。我们碰到一个数number就把它直接存到HashTable里面,这样直接查找target - number就可以找出two sum并且不用像上面的代码skip掉相同Index和比较index的大小了。这里照搬Leetcode的CleanCodeHandbook的代码。

    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            int x = numbers[i];
            if (map.containsKey(target - x)) {
                return new int[] { map.get(target - x) + 1, i + 1 };
            }
            map.put(x, i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

Two Sum II – Input array is sorted

Similar to Question [1. Two Sum], except that the input array is already sorted in ascending order.

因为有序,直接想到双指针。O(n) runtime, O(1) space。照搬Leetcode的CleanCodeHandbook的代码。

    public int[] twoSum(int[] numbers, int target) {
        // Assume input is already sorted.
        int i = 0, j = numbers.length - 1;
        while (i < j) {
            int sum = numbers[i] + numbers[j];
            if (sum < target) {
                i++;
            } else if (sum > target) {
                j--; 
            } else {
                return new int[] { i + 1, j + 1 }; 
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

Two Sum III – Data structure design

Design and implement a TwoSum class. It should support the following operations: add and find.
add(input) – Add the number input to an internal data structure.
find(value) – Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5); find(4)true; find(7)false

add – O(1) runtime, find – O(n) runtime, O(n) space

    public class TwoSum {
        private Map<Integer, Integer> table = new HashMap<>();
        public void add(int input) {
            int count = table.containsKey(input) ? table.get(input) : 0;
            table.put(input, count + 1);
        }
        public boolean find(int val) {
            for (Map.Entry<Integer, Integer> entry : table.entrySet()) {
                int num = entry.getKey();
                int y = val - num;
                if (y == num) {
                    // For duplicates, ensure there are at least two individual numbers.
                    if (entry.getValue() >= 2) return true;
                } else if (table.containsKey(y)) {
                    return true;
                }
            }
            return false;
        }
    }

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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)

先sort数组,然后枚举a, b, c。因为有序,可以双指针找b, c。
Time Complexity: O(n ^ 2) Space Complexity: O(1)

public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(num);
        for(int i = 0; i < num.length - 2; i++){
        //Skip duplicates of a
            if(i != 0 && num[i] == num[i - 1]){
                continue;
            }
            int a = num[i], left = i + 1, right = num.length - 1;
            while(left < right){
                int b = num[left], c = num[right];
                if(a + b + c == 0){
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(a); list.add(b); list.add(c);
                    result.add(list);
                    //Skip duplicates of b
                    while(left < right && num[left] == num[left + 1]) left++;
                    //Skip duplicates of c
                    while(left < right && num[right] == num[right - 1]) right--;
                    left++; right--;
                }else if(b + c < -a){
                    left++;
                }else{
                    right--;
                }
            }
        }
        return result;
    }
}

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).

类似3Sum做法。Time Complexity: O(n ^ 2) Space Complexity: O(1)

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int closest = Integer.MAX_VALUE / 2;
        int start, end;
        for(int i = 0; i < num.length - 1; i++){
            start = i + 1;
            end = num.length - 1;
            while(start < end){
                int sum = num[i] + num[start] + num[end];
                if(sum == target){
                    return sum;
                }else if(sum < target){
                    start++;
                }else{
                    end--;
                }
                closest = Math.abs(closest - target) > Math.abs(sum - target) ? sum : closest;
            }
        }
        return closest;
    }
}

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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
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)

类似3Sum,先排序,再枚举a, b。双指针枚举c, d。

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int n = num.length;
        Arrays.sort(num);
        for(int i = 0; i < n; i++){
            if(i != 0 && num[i] == num[i - 1]){
                continue;
            }
            for(int j = i + 1; j < n; j++){
                if(j != i + 1 && num[j] == num[j - 1]){
                    continue;
                }
                int start = j + 1, end = n - 1;
                while(start < end){
                    int a = num[i];
                    int b = num[j];
                    int c = num[start];
                    int d = num[end];
                    if(a + b + c + d == target){
                        List<Integer> res = new ArrayList<Integer>();
                        res.add(a);
                        res.add(b);
                        res.add(c);
                        res.add(d);
                        result.add(res);
                        start++; end--;
                        while(start < end && num[start] == num[start - 1])
                            start++;
                        while(start < end && num[end] == num[end + 1])
                            end--;
                    }else if(a + b + c + d < target){
                        start++;
                    }else{
                        end--;
                    }
                }
            }
        }
        return result;
    }
}

k Sum

Given n distinct positive integers, integer k (k <= n) and a number target.
Find k numbers where sum is target. Calculate how many solutions there are?

Example
Given [1,2,3,4], k=2, target=5. There are 2 solutions:
[1,4] and [2,3], return 2.

三维DP。dp[i][k][m]表示前i个数中选k个数的sum等于m。
转移方式: 1. dp[i][k][m] = dp[i - 1][k][m] (not choose A[i] into result)
2. dp[i][k][m] = dp[i - 1][k - 1][m - A[i]](choose A[i] into result)

public class Solution {
    /**
     * @param A: an integer array.
     * @param k: a positive integer (k <= length(A))
     * @param target: a integer
     * @return an integer
     */
    public int  kSum(int A[], int k, int target) {
        int n = A.length;
        int[][][] dp = new int[A.length + 1][k + 1][target + 1];
        dp[0][0][0] = 1;
        for(int i = 1; i <= n; ++i)
        for(int j = 0; j <= i && j <= k; ++j)
        for(int s = 0; s <= target; ++s){
            dp[i][j][s] = dp[i - 1][j][s];//not choose A[i]
            if(j > 0 && s >= A[i - 1]){
                dp[i][j][s] += dp[i - 1][j - 1][s - A[i - 1]];
                }
        }
        return dp[n][k][target];
    }
}

k Sum II

Given n unique integers, number k (1<=k<=n) and target. Find all possible k integers where their sum is target.

Example
Given [1,2,3,4], k=2, target=5, [1,4] and [2,3] are possible solutions.

思路:DFS搜索。

public class Solution {
    /**
     * @param A: an integer array.
     * @param k: a positive integer (k <= length(A))
     * @param target: a integer
     * @return a list of lists of integer 
     */ 
    public ArrayList<ArrayList<Integer>> kSumII(int A[], int k, int target) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        helper(result, list, A, k, target, 0);
        return result;
    }

    private void helper(ArrayList<ArrayList<Integer>> result, 
        ArrayList<Integer> list, int[] A, int k, int target, int pos){
        if(list.size() == k && target == 0){
            result.add(new ArrayList<Integer>(list));
            return;
        }else if(list.size() > k){
            return;
        }
        for(int i = pos; i < A.length; i++){
            list.add(A[i]);
            helper(result, list, A, k, target - A[i], i + 1);
            list.remove(list.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值