2017.9.10
数组是有序的,因此从low和height相加。
如果结果大于给定的值,那么height--;
如果结果小于给定的值,那么low++;
public class Solution {
/*
* @param nums: an array of Integer
* @param target: target = nums[index1] + nums[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] nums, int target) {
// write your code here
int length = nums.length;
if(length <=1){
return null;
}
int []res = new int[2];
int low = 0;
int height = length -1;
while(low < height){
if(nums[low] + nums[height] == target){
res[0] = low + 1;
res[1] = height + 1;
break;
}
while(low < height && nums[low] + nums[height] < target){
low ++;
}
while(low < height && nums[low] + nums[height] > target){
height--;
}
}
return res;
}
}
本文介绍了一种解决有序数组中寻找两个数使它们的和等于特定目标值的问题的方法。通过双指针技术,该算法有效地实现了搜索过程,提高了查找效率。
396

被折叠的 条评论
为什么被折叠?



