算法通关村——n数之和问题解析

n数之和:

本文主要针对两数之和和三数之和问题进行分析和解决

两数之和:

题目:LeetCode1. 给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。

本题两种主要的解题思路,一种就是暴力循环。直接两层for循环进行嵌套,对于每一个数x都去通过循环找到对应的target-x。但时间复杂度过高。

另一种则是利用Hash去进行操作,用空间换时间。循环遍历判断当前数x,是否在hashmap里面存在key为target-x。如果存在则找到,不存在则将当前x和其下标存到map当中。具体实现如下。

public class TwoSumCLone {
    public static int[] twoSum(int[] nums, int target) {
        HashMap<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 null;
    }

}

三数之和

题目:LeetCode15.给你一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a+b+c = 0 ?请你找出所有和为0且不重复的三元组。注意:答案中不可以包含重复的三元组。

本题虽然相较于上一题只增加了一个数,但是思路和难度变化很多。首先三层嵌套循环也可以,但时间复杂度太大O(n^3)。或者双层循环确定target再利用Hash实现,沿用上一题思路,用循环确定target从而使用Hash操作。

本题我们使用“排序+双指针”的思想。先将数组排序,方便处理重复结果,然后固定一位元素,才用双指针求解,具体实现如下:

public class ThreeSumClone {
    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        List<List<Integer>> list = threeSum(nums);
        System.out.println(list);

    }
    public static List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        ArrayList<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int first = 0; first < n; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int third = n - 1;
            int target = -nums[first];
            for (int second = first + 1; second < n; second++) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while (second < third && nums[second] + nums[third] > target) {
                    third--;
                }
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    result.add(list);
                }
            }
        }
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值