两个数的和||

给定一个排序数组,求出其中两个数的和等于指定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是收费才能做的题目

相关文章:

  • 2021-12-28
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
猜你喜欢
  • 2021-11-27
  • 2021-05-31
  • 2021-07-09
  • 2022-01-19
  • 2021-07-01
  • 2021-12-31
  • 2022-01-17
相关资源
相似解决方案