LeetCode--两数之和

文章详细介绍了多种求解两数之和问题的方法,包括暴力查找、哈希查找及其优化,以及针对不同场景如乱序、顺序、数据结构设计和输入BST的应用。此外,还探讨了三数之和的解法,如双指针查找和去重技巧,并提供了Java实现。
摘要由CSDN通过智能技术生成

1.两数之和

1.1 两数之和-乱序(题号1)

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

注意: 你可以假设每种输入只会对应一个答案。 数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。

示例 1:

输入:numbers = [2,7,11,15], target = 9
输出:[0,1]

思路:固定一个数x,再剩下的数里找target-x,题目转变成了查找题。

1.1.1 暴力查找

public class Solution1 {
    public int[] twoSum(int[] sums,int target){
        if (sums == null || sums.length == 0) return new int[0];
        for (int i = 0; i < sums.length; i++) {
            int x = sums[i];
            for (int j = i+1 ;j < sums.length ;j++){
                if (sums[j] == target - x) return new int[]{i,j};
            }
        }
        return new int[0];
    }
}

1.1.2 一般哈希查找

public class Solution2 {
    public int[] twoSum(int nums[] ,int target){
        if (nums == null || nums.length == 0) return new int[0];

        Map<Integer,Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i],i);
        }
        for (int i = 0; i < nums.length; i++) {
            int x = nums[i];
            if (map.containsKey(target-x)){
                int index = map.get(target-x);
                if (index != i) return new int[]{i,index};
            }
        }
        return new int[0];
    }
}

1.1.2 优化哈希查找

public class Solution3 {
    public int[] twoSum(int[] sums,int target) {
        if (sums == null || sums.length == 0) return new int[0];

        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < sums.length; i++) {
            int x = sums[i];
            if (map.containsKey(target-x)){
                int index = map.get(target-x);
                return new int[]{i,index};
            }
            map.put(sums[i],i);
        }
        return new int[0];
    }
}

思考:

  • 哈希表key存放数字,value存放标,如果数字重复下标也会被更新。
  • 一般哈希查找如果出现重复数字,返回的是重复数字最大下标
  • 优化哈希查找如果出现重复数字,返回的是重复数字的最小下标

根据题意只需返回任意一组,所以都符合题意

1.2 两数之和II-顺序(题号167)

题目:
给你一个下标从 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] 。

1.2.1 二分查找法

    public int[] twoSum(int nums[],int target){

        for (int i = 0; i < nums.length; i++) {
            int x = nums[i];
            int index = this.binaryFind(nums, i + 1, nums.length - 1, target - x);
            if (index != -1){
                return new int[]{i+1,index+1};
            }
        }
        return new int[0];
    }

    public int binaryFind(int[] nums ,int left ,int right ,int key){
        while (left<=right){
            int mid = (left+right)/2;
            if (nums[mid] == key){
                return mid;
            }else if (nums[mid] > key){
                right--;
            }else {
                left++;
            }
        }
        return -1;
    }

1.2.2 左右指针法

    public int[] twoSum(int nums[],int target){
        int left = 0;
        int right = nums.length-1;
        while (left<right){
            if (nums[left]+nums[right]==target){
                return new int[]{left+1,right+1};
            }else if (nums[left]+nums[right]>=target){
                right--;
            }else {
                left++;
            }
        }
        return new int[0];
    }

1.3 两数之和III-数据结构设计(题号170)

题目:
无序且可以添加的一组数。
能判断即可,不需返回索引值。

思考:
可以添加需要设计成List数据类型。
为使其有序可以采用Collections.sort()对ArrayList排序。
在添加时需重新排序,不添加时不需排序可优化代码。

1.3.1 左右指针法优化

public class Solution1 {
    private List<Integer> nums;
    private boolean isSorted;

    public Solution1() {
        nums = new ArrayList<>() ;
        isSorted = false;
    }

    public Solution1(List<Integer> nums) {
        this.nums = nums;
    }

    void add(int num){
        this.nums.add(num);
        isSorted=false;
    }

    boolean twoSum(int target){
        if (!isSorted){
            Collections.sort(nums);
            isSorted = true;
        }

        int left = 0;
        int right = nums.size()-1;
        while (left<right){
            if (nums.get(left)+nums.get(right)==target){
                return true;
            }else if (nums.get(left)+nums.get(right)>target){
                right--;
            }else {
                left++;
            }
        }
        return false;
    }
}

1.3.2 哈希查找

public class Solution2 {
    private Set<Integer> nums;


    public Solution2(){
        nums = new HashSet<>();
    }

    void add(int num){
        this.nums.add(num);
    }


    boolean twoSum(int target) {
        for (Integer num:nums){
            int x = target - num;
            if (x != num && nums.contains(x)){
                return true;
            }
        }
        return false;
    }
}

思考:
左右指针适用于有重复数字出现的情况,比如5+5=10;
哈希查找不允许;

1.4 两数之和IV-输入BST(题号653)

补充二叉搜索树(二叉排序树/二叉查找树)概念:

  1. 它或者是一棵空树
  2. 或者是具有下列性质的 二叉树 :
    • 若它的左子树不空,则左子树上所有结点的值均小于它的 根结点 的值;
    • 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
    • 它的左、右子树也分别为 二叉排序树 。

题目:
给定一个二叉搜索树 root 和一个目标结果 k,如果二叉搜索树中存在两个元素且它们的和等于给定的目标结果,则返回 true。
示例:
在这里插入图片描述

输入: root = [5,3,6,2,4,null,7], k = 9
输出: true

1.4.1 双指针查找法

对于二叉搜索树使用中序遍历即可得到有序数组,按1.2的方法对其进行查找

    public boolean findTarget(TreeNode root, int k) {
        if (root == null) return false;
        List<Integer> nums = new ArrayList<>();
        inOrder(root,nums);

        int left = 0;
        int right = nums.size()-1;
        while (left<right){
            if (nums.get(left)+nums.get(right)==k){
                return true;
            }else if (nums.get(left)+nums.get(right)>k){
                right--;
            }else {
                left++;
            }
        }
        return false;
    }
	/**
	*中序遍历二叉树(递归遍历)
	*/
    void inOrder(TreeNode root,List nums){
        if (root == null) return;
        inOrder(root.left,nums);
        nums.add(root.val);
        inOrder(root.right, nums);
    }

1.4.2 一次哈希遍历查找

    public boolean findTarget(TreeNode root, int k) {
        if (root == null) return false;
        Set<Integer> nums = new HashSet<>();
        return find(root,k,nums);
    }
	/*在遍历的基础上直接添加元素,数组使用for循环遍历,树要通过递归遍历*/
    boolean find(TreeNode node,int target,Set nums){
        if (node == null) return false;
        if (nums.contains(target-node.val)) return true;
        nums.add(node.val);
        return (find(node.left,target,nums) || find(node.right,target,nums));
    }

2. 三数之和

题目:
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。

2.1 暴力查找

    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> res = new HashSet<>();
        if (nums == null || nums.length < 3) return null;
		
		//优化:一次排序
		Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j< nums.length;j++){
                for (int k = j+1; k < nums.length;k++){
                    if (nums[i]+nums[j]+nums[k]==0){
                        List<Integer> tmp = Arrays.asList(nums[i],nums[j],nums[k]);
                        //去重!!排序后利用set不可重复性去重
                        //Collections.sort(tmp);
                        res.add(tmp);
                    }
                }
            }
        }
        return new ArrayList<>(res);
    }

2.1 双指针查找

思考:
三个数固定一个数(如果剩下的数不足两个数就不用找了),剩下的问题就变成两数之和问题。
注意:
要找到所有符合的组合,循环要遍历完全。
双指针if语句的逻辑,找到了也要移动一下指针,否则会死循环。
使用Set去重

    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> res = new HashSet<>();
        if (nums == null || nums.length < 3) return null;
        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[left]+nums[right]+nums[i];
                if (sum==0) {
                	res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                	left++;
           		}else if (sum>0){
                    right--;
                }else {
                    left++;
                }
            }
        }
        return new ArrayList<>(res);//O(n)
    }

2.1 双指针查找优化(去重小技巧)

思路:在遍历过程中如果遇到相同的数就跳过。
思考:这种去重思路是建立在有序数组的基础上,重复的数字会连续出现。

    public List<List<Integer>> threeSum(int[] nums) {
       // Set<Integer> set = Arrays.stream(nums).collect(Collectors.toSet());
        List<List<Integer>> res = new ArrayList<>();

        if (nums == null || nums.length < 3) return null;
        Arrays.sort(nums);

        for (int i = 0; i < nums.length-2; i++) {
            if ( i>0 && nums[i]==nums[i-1]) continue;
            int left = i+1;
            int right = nums.length-1;

            while (left<right){
                int sum = nums[left]+nums[right]+nums[i];
                //需要使用两个if,不能全部连起来
                if (sum==0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left<right && nums[left]==nums[++left]);
                    while (left<right && nums[right]==nums[--right]);
                }else if (sum>0){
                    right--;
                }else {
                    left++;
                }
            }
        }
        return (res);
    }

拓展:如果四数之和,就固定两个数,其余思路相同。

常用Java方法总结

将数组放入集合:

  1. 手动遍历添加
  2. 使用构造方法添加
  3. 不能使用addAll(集合,元素)方法:第二个参数是元素所以不能放入数组,数组不是集合的元素,数组里的元素才是集合的元素。
Integer[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<>(Arrays.asList(arr));

排序:

Collections.sort(集合名称)
Arrays.sort(数组名称)

流:

Set<Integer> set = Arrays.stream(nums).collect(Collectors.toSet());
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值