剑指Offer57:和为s的两个数字(Java)

题目描述:
在这里插入图片描述
解法1:
    这种解法是通过HashSet去解决它。道理很简单,遍历数组,因为题目说两个数相加等于target,那我就把target减去每个数剩下值存入set中。每次存入时先判断set是否已经有存在这个数,如果有,则证明在这个数之前,有一个数和现在的数相加等于target。那么返回一个包含这两个数的数组即可。但是这种方法效率不高。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Set<Integer> set = new HashSet<>();
        int[] res = new int[2];
        for(int i = 0; i < nums.length; i++){
            if(set.contains(nums[i])) {
                res[0] = nums[i]; res[1] = target - nums[i];
            }
            else set.add(target - nums[i]);
        }
        return res;
    }
}

在这里插入图片描述

解法2:
    这种解法是通过双指针去解决这道题。首先我们定义双指针,一个在数组头,一个在数组尾。通过while循环,比较两个指针的元素和以及target,如果比target大,那么尾指针就向后移;如果比target小,头指针就向后移;只要头尾指针不相碰,就一直循环下去。当循环中,发现两指针的元素和等于target时,返回包含两指针元素的数组即可。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int i = 0, j = nums.length - 1;
        while(i < j) {
            int s = nums[i] + nums[j];
            if(s < target) i++;
            else if(s > target) j--;
            else{
                res[0] = nums[i]; res[1] = nums[j]; return res;
            }
        }
        return res;
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值