【Description】
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.
【AC code】
一、暴力法 时间复杂度:O(n^2)
1 class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int arrlen = numbers.length; 4 for (int i = 0; i < arrlen - 1; i++) { 5 for (int j = i + 1; j < arrlen; j++) { 6 if (numbers[i] + numbers[j] == target) return new int[]{i + 1, j + 1}; 7 } 8 } 9 return new int[]{}; 10 } 11 }
二、二分查找法 时间复杂度:O(nlogn)
1 class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int arrlen = numbers.length; 4 for (int i = 0; i < arrlen; i++) { 5 int left = i + 1, right = arrlen - 1; 6 while (left <= right) { 7 int mid = left + (right - left) / 2; 8 int tmp = numbers[i] + numbers[mid]; 9 if (tmp > target) right = mid - 1; 10 else if (tmp < target) left = mid + 1; 11 else return new int[]{i + 1, mid + 1}; 12 } 13 } 14 return new int[]{}; 15 } 16 }
三、双索引法 时间复杂度:O(n)
1 class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int left = 0, right = numbers.length - 1; 4 while (left < right) { 5 int tmp = numbers[left] + numbers[right]; 6 if (tmp == target) return new int[]{left + 1, right + 1}; 7 else if (tmp > target) right--; 8 else left++; 9 } 10 return new int[]{}; 11 } 12 }