一、题目描述
二、解法
思路1:双指针。最优解,时间复杂度为O(n)
思路2:二分搜索。 (Tips:看见 数组 + 有序,第一时间想到 二分!!)
时间复杂度:O(nlogn),其中二分的复杂度为O(logn)
class Solution { public int[] twoSum(int[] numbers, int target) { int low = 0, high = numbers.length - 1; while (low < high) { if (numbers[low] + numbers[high] == target) { return new int[]{low + 1, high + 1}; }else if (numbers[low] + numbers[high] > target) { high--; }else { low++; } } return new int[]{-1,-1}; /** * 方法2:二分 * 注意:写二分时一定要注意 循环不变量的定义!! */ /*int[] res = new int[2]; for (int i = 0; i < numbers.length - 1; i++) { int low = i + 1; int high = numbers.length - 1; while (low <= high) { // low = high时,区间仍是有效的 int mid = low + ((high - low) >> 1); if (numbers[mid] == target - numbers[i]) { res[0] = i + 1; res[1] = mid + 1; return res; }else if (numbers[mid] > target - numbers[i]) { high = mid - 1; }else { // numbers[mid] < target - numbers[i] low = mid + 1; } } } return res;*/ } }