剑指offer 57:和为s的两个数字

先放图:

先说传统的暴力解法,就是用双重循环,先固定一个数,然后从它后面的数字去找。时间复杂度为O(n^2),面试时肯定不行的。不过剑指说面试时有思路可以立即说出来,反映你思维敏捷。。

放下暴力解法代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null) return null;
        int l = 0, h = 0;
        for (int i = 0; i <= nums.length - 2; i++) {
            for (int j = i + 1; j <= nums.length - 1; j++) {
                if ((nums[i] + nums[j]) == target) {
                    l = i;
                    h = j;
                    break;
                }
            }
        }
        return new int[] {nums[l], nums[h]};
    }
}

接下来介绍面试解法:用双指针,初始时刻一个指向第一个数,另一个指针指向最后一个数(即最大的数)。用两个指针来判断,若和比target小,则逐渐增加较小的数;若和比target还大,则迅速减小较大的数。(指针移动的方向)

我的代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null) return null;
        int low = 0, high = nums.length - 1;
        while (low < high) {
            int tmp = nums[low] + nums[high];
            if (tmp == target) break;
            else if (tmp > target) high--;
            else low++;
        }
        return new int[] {nums[low], nums[high]};
    }
}

常见大佬的代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        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 return new int[] { nums[i], nums[j] };
        }
        return new int[0];
    }
}

作者:jyd
链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/solution/mian-shi-ti-57-he-wei-s-de-liang-ge-shu-zi-shuang-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

时间复杂度:O(n^2),空间复杂度:O(1) 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值