有序数组,找出两数之和等于target
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
leetcode 链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
针对有序数组的输入,使用双指针,时间复杂度O(n),空间复杂度O(1):
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0; //左指针
int right = numbers.length-1; //右指针
while(left!=right){
if((numbers[left]+numbers[right])==target)
return new int[]{left+1,right+1};
if((numbers[left]+numbers[right])>target){ //和大于目标值,右指针左移
right--;
}else{ //和小于目标值,做指针右移
left++;
}
}
return null;
}
}
针对无序数组或有序数组的输入,使用HashMap,时间复杂度为O(n),空间复杂度O(n):
class Solution {
public int[] twoSum(int[] numbers, int target) {
//针对无序数组
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < numbers.length; i ++){
if(map.containsKey(target-numbers[i])){
return new int[]{map.get(target-numbers[i]),i+1}; //存在
}else{
map.put(numbers[i],i+1);
}
}
return null;
}
}