【Leetcode】167. Two Sum II - Input array is sorted(Easy)

1.题目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

翻译:给定一个已经升序排列的整数序列,找到两个数字相加等于一个目标数字。twoSum方法应该返回相加等于目标值的两个数字的序列索引,第一个索引值小于第二个。这两个返回值都不是从零开始的。
2.思路

错误思路:外层循环i,从0开始遍历数组中的每一个数,内存循环j 判断是否有数字与其相加符合条件。这个暴力算法第一次很偶然的被Accepted了,但是之后再怎么提交都不通过啦。

正确思路:这道算法题应该采用“双指针”的思路。i从0开始,j从‘数组长度-1‘ 开始。

当i<j时,循环计算。(此处不应是i<=j,因为index1必须小于index2,即同一个数不能重复利用)

①当nums[i]+nums[j]<target时,说明 i 应该右移。(数组是升序排列的)

②当nums[i]+nums[j]>target时,说明 j 应该左移。

③返回i+1 和 j+1 (索引不是从0开始的)

3.算法

①暴力算法,偶然Accepted

public int[] twoSum(int[] numbers, int target) {
        //Accepted occasionally
         int[] res=new int[2];
         int n=numbers.length;
         for(int i=0;i<n;i++){
             for(int j=n-1;j>i;j--){
                 if(numbers[i]+numbers[j]==target){
                     res[0]=i+1;
                     res[1]=j+1;
                     return res;
                 }
             }
         }
        
        return res;
 }

②‘ 双指针‘思路 (Accepted) 

public int[] twoSum(int[] numbers, int target) {
        int[] res=new int[2];
        int n=numbers.length;
        int low=0;
        int high=n-1;
        
        while(low<high){
            if(numbers[low]+numbers[high]<target){
                low++;
            }else if(numbers[low]+numbers[high]>target){
                high--;
            }else{
                res[0]=low+1;
                res[1]=high+1;
                return res;
            }
        }
        return res;
        
    }

4.总结

 1.培养双指针的思路,双向同时移动,提高效率。

2.其实这个算法应该还有改进之处,两个数相加的步骤是可能发生溢出的。看了一些文章有两张办法,一种是使用long型避免溢出,

还一种是 使用 减法代替加法。在该题中,即时用target-nums[i]与nums[j]进行比较。





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值