两数之和-------------------------Two Sum II - Input array is sorted-LeetCode167

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.
 //只需要两个指针,A指向索引0,B指向索引len - 1,根据值和目标比较缩小范围。o(n)复杂度
    public int[] twoSum(int[] numbers, int target) {
        int[] indice = new int[2];
    if (numbers == null || numbers.length < 2) return indice;
    int left = 0, right = numbers.length - 1;
    while (left < right) {
        int v = numbers[left] + numbers[right];
        if (v == target) {
            indice[0] = left + 1;
            indice[1] = right + 1;
            break;
        } else if (v > target) {//末尾的值太大,缩小范围
            right --;
        } else {//前面的值太小
            left ++;
        }
    }
    return indice;

        
    }



//最常规的思路 o(n^2)复杂度
  public int[] twoSum(int[] numbers, int target) {
		 // int[] res=new int[2];
		 // for(int i=0;i<numbers.length;i++)
		 // {
		 // int temp=numbers[i];
		 // for(int j=i+1;j<numbers.length;j++)
		 // if(target-temp==numbers[j])
		 // {
		 // res[0]=i+1;
		 // res[1]=j+1;
		 // }
		 // }
		 // return res;
}

猜你喜欢

转载自blog.csdn.net/si444555666777/article/details/81264528
今日推荐