您的位置:首页 > 其它

leetcode:两个数的和||

2015-10-26 21:05 155 查看
两个数的和||

给定一个排序数组,求出其中两个数的和等于指定target时,这两个数在原始数组中的下标,返回的下标从1开始

解题

原始数组已经是升序的,找出其中两个数的和等于target

定义两个指针,left right

计算x = num[left] + num[right] 的值

等于target 返回下标

小于target,说明需要增大这两个数,然后num[right] 已经是最大的数了,我们只有增加num[left],通过left++ 来增加

大于target right--

public class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length == 0)
return null;
int i = 0;
int j = nums.length -1;
while(i<j){
int x = nums[i] + nums[j];
if(x< target)
i++;
else if(i> target)
j--;
else
return new int[]{i+1,j+1};
}
return null;
}
}


说明:LeetCode是收费才能做的题目
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: