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。
感觉自己在进步,哦呵呵。