codetop求和问题

文章介绍了在给定整数数组中寻找两个数,其和等于目标值的高效算法,包括使用哈希表和排序的方法。重点讨论了如何在常量空间复杂度内解决这个问题,并提供了几种可能的实现方式。
摘要由CSDN通过智能技术生成

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] = target) {
                    return new int[]{i, j};
                }
            }
        }
    }
}

 

那么如何快速知道o(n)的信息呢,一种是通过哈希表,另一种则是排序,如果某两个数值大,后面肯定大。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 需要查询target - nums[i] 的位置
        // 需要准确定位这个元素的位置,最好的办法就是存入map
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target- nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}
class Solution {
    // 因为要返回下标,我们排序会把下标修改,所以需要知道每个元素所对应的下标是多少,如何做呢?考虑下标数组,我们通过下标数组排序,下标数组中是有序的,我们取下标数组对应元素对应原数组的值,即也是有序的,这样返回下下标数组对应下标的值,即为原下标。
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int i = 0, j = n - 1;
        Integer[] idxs = new Integer[n];
        for (int idx = 0; idx < n; idx++) {
            idxs[idx] = idx;
        }
        Arrays.sort(idxs, (i1, i2) -> nums[i1] - nums[i2]);
        while (i < j) {
            if (nums[idxs[i]] + nums[idxs[j]] == target) {
                return new int[]{idxs[i], idxs[j]};
            }else if (nums[idxs[i]] + nums[idxs[j]] < target) {
                i++;
            }else {
                j--;
            }
        }
        return new int[0];
    }
}

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1。

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement)) {
                // numMap.get(complement)得到的是之前存储的较小的索引
                // i 是当前的较大的索引
                return new int[] { numMap.get(complement), i };
            }
            numMap.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] numbers = {2, 7, 11, 15};
        int target = 9;
        int[] indices = solution.twoSum(numbers, target);
        System.out.println("Index1: " + indices[0] + ", Index2: " + indices[1]);
    }
}

设计并实现一个 TwoSum 类。他需要支持以下操作:add 和 find
add -把这个数添加到内部的数据结构。
find -是否存在任意一对数字之和等于这个值

import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    private Map<Integer, Integer> numCounts;

    /** Initialize your data structure here. */
    public TwoSum() {
        numCounts = new HashMap<>();
    }

    /** Add the number to an internal data structure.. */
    public void add(int number) {
        numCounts.put(number, numCounts.getOrDefault(number, 0) + 1);
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for (Map.Entry<Integer, Integer> entry : numCounts.entrySet()) {
            int num = entry.getKey();
            int complement = value - num;
            if (complement != num) {
                // If the complement is different from the number,
                // check if it exists in the map
                if (numCounts.containsKey(complement)) {
                    return true;
                }
            } else {
                // If the complement is the same as the number,
                // check if there is more than one instance
                if (entry.getValue() > 1) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        TwoSum twoSum = new TwoSum();
        twoSum.add(1);
        twoSum.add(3);
        twoSum.add(5);
        System.out.println(twoSum.find(4));  // true, 1 + 3 = 4
        System.out.println(twoSum.find(7));  // true, 3 + 4 = 7
        System.out.println(twoSum.find(2));  // false, no two numbers add up to 2
    }
}

给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列  ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。

以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1  index2

你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。

你所设计的解决方案必须只使用常量级的额外空间。

 

示例 1:

输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (true) {
            if (nums[left] + nums[right] == target) {
                return new int[]{left + 1, right + 1};
            }else if (nums[left] + nums[right] < target) {
                left++;
            }else {
                right--;
            }
        }
    }
}

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        return nSumTarget(nums, 3, 0, 0);
    }

    private List<List<Integer>> nSumTarget(int[] nums, int n, int start, int target) {
        int length = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if (length < 2 || length < n) {
            return res;
        }
        if (n == 2) {
            int lo = start, hi = length - 1;
            while (lo < hi) {
                int sum = nums[lo] + nums[hi];
                int left = nums[lo], right = nums[hi];
                if (sum < target) {
                    while (lo < hi && nums[lo] == left) {
                        lo++;
                    }
                }else if (sum > target) {
                    while (lo < hi && nums[hi] == right) {
                        hi--;
                    }
                }else {
                    res.add(new ArrayList<>(Arrays.asList(left, right)));
                    while (lo < hi && nums[lo] == left) {
                        lo++;
                    }
                    while (lo < hi && nums[hi] == right) {
                        hi--;
                    }
                }
            }
        }else {
            for (int i = start; i < length; i++) {
                List<List<Integer>> subs = nSumTarget(nums, n - 1, i + 1, target - nums[i]);
                for (List<Integer> sub : subs) {
                    sub.add(nums[i]);
                    res.add(sub);
                }
                 while (i < length - 1 && nums[i] == nums[i + 1]) {
                     i++;
                 }

            }
        }
        return res;
    }
}
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        // i < j < k 所以需要留两个位置给j和k
        for (int i = 0; i < n - 2; i++) {
            int x = nums[i];
            // 把最初的重复元素遍历掉,考虑循环不变量,i为当前看到的元素,保证i之前的是没有重复的;
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int j = i + 1, k = n - 1;
            while (j < k) {
                int sum = x + nums[j] + nums[k];
                if (sum < 0) {
                    j++;
                }else if (sum > 0) {
                    k--;
                }else {
                    res.add(new ArrayList<>(Arrays.asList(x, nums[j], nums[k])));
                    ++j;
                    while (j < k && nums[j] == nums[j - 1]) {
                        j++;
                    }
                    --k;
                    // [j, k]无重复元素
                    while (j < k && nums[k] == nums[k + 1]) {
                        k--;
                    }
                }
            }
        }
        return res;
    }
}

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):

  • 0 <= a, b, c, d < n
  • abc 和 d 互不相同
  • nums[a] + nums[b] + nums[c] + nums[d] == target

你可以按 任意顺序 返回答案 。

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        return nSumTarget(nums, 4, 0, target);
    }

    private List<List<Integer>> nSumTarget(int[] nums, int n, int start, int target) {
        int length = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        if (length < 2 || length < n) {
            return res;
        }
        if (n == 2) {
            int lo = start, hi = length - 1;
            while (lo < hi) {
                int sum = 0L + nums[lo] + nums[hi];
                int left = nums[lo], right = nums[hi];
                if (sum < target) {
                    while (lo < hi && nums[lo] == left) {
                        lo++;
                    }
                }else if (sum > target) {
                    while (lo < hi && nums[hi] == right) {
                        hi--;
                    }
                }else {
                    res.add(new ArrayList<>(Arrays.asList(left, right)));
                    while (lo < hi && nums[lo] == left) {
                        lo++;
                    }
                    while (lo < hi && nums[hi] == right) {
                        hi--;
                    }
                }
            }
        }else {
            for (int i = start; i < length; i++) {
                List<List<Integer>> subs = nSumTarget(nums, n - 1, i + 1, target - nums[i]);
                for (List<Integer> sub : subs) {
                    sub.add(nums[i]);
                    res.add(sub);
                }
                while (i < length -1 && nums[i] == nums[i + 1]) {
                    i++;
                }
            }
        }
        return res;
    }
}
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        for (int a = 0; a < n - 3; a++) {
            long x = nums[a];
            if (a > 0 && nums[a] == nums[a - 1]) {
                continue;
            }
            for (int b = a + 1; b < n - 2; b++) {
                long y = nums[b];
                if (b > a + 1 && nums[b] == nums[b - 1]) {
                    continue;
                }
                int c = b + 1, d = n - 1;
                while (c < d) {
                    long sum = x + y + nums[c] + nums[d];
                    if (sum > target) {
                        d--;
                    }else if (sum < target) {
                        c++;
                    }else {
                        res.add(new ArrayList<>(Arrays.asList((int)x, (int)y, nums[c], nums[d])));
                        ++c;
                        while (c < d && nums[c] == nums[c - 1]) {
                            c++;
                        }
                        --d;
                        while (c < d && nums[d] == nums[d + 1]) {
                            d--;
                        }
                    }
                }
            }
        }
        return res;
    }
}

给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。

返回这三个数的和。

假定每组输入只存在恰好一个解。

示例 1:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int ans = 0;
        int minDiff = Integer.MAX_VALUE;
        for (int i = 0; i < n - 2; i++) {
            int x = nums[i];
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1, k = n - 1;
            while (j < k) {
                int sum = x + nums[j] + nums[k];
                if (sum > target) {
                    if (sum - target < minDiff) {
                        minDiff = sum - target;
                        ans = sum;
                    }
                    k--;
                }else {
                    if (target - sum < minDiff) {
                        minDiff = target - sum;
                        ans = sum;
                    }
                    j++;
                }
            }
        }
        return ans;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值