LeetCode刷题(Java)——2. Two Sum II - Input array is sorted

Question:

 

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.

Note:

  • 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.

 

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

有上一题的铺垫,这一题很明确就是为了减少空间复杂度,数组是有序的,那是不是意味着可以不用每个数都循环,如果数组中的某个值比目标值大,是不是就可以跳出循环了?基于这个思路写了如下代码:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result= new int[2];
        Map<Integer,Integer> map = new HashMap();
        for (int i=0;i<numbers.length;i++){
            if((numbers[i]>target)&&(target>0)){
                break;
            }
            else if((map.containsKey(target-numbers[i])) ){
                result[0] = map.get(target-numbers[i]);
                result[1] = i+1;
                return result;
            }
            map.put(numbers[i],i+1);
        }
        return result;
    }
}

最开始的代码提交后提示[-1,0],我的答案是[0.0],期盼的答案是[1,2],所以我在代码里加了“&&(target>0)”,按理说这样写肯定是过不了的,比如给出如下的数组:

 

[-11,2,3,5,15]
4

输出结果就是错误的,大家可以试试,但是竟然AC了……

所以小伙伴们一定不能为了刷题而刷题,然后本娃子就去看前辈们写的代码了,因为暂时没有想到比上面的方法更优的方法了,看懂方法后重新被AC:

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

后面的方法空间复杂度为O(1),时间复杂度为O(n),运行时间为1ms,之前那个运行时间为2ms。

感觉自己在进步,哦呵呵。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值