題目描述:
給定一個按照升序排列的整數數組 nums,和一個目標值 target。找出給定目標值在數組中的開始位置和結束位置。
你的算法時間複雜度必須是 O(log n) 級別。
如果數組中不存在目標值,返回 [-1, -1]。
示例 1:
輸入: nums = [5,7,7,8,8,10], target = 8
輸出: [3,4]
示例 2:
輸入: nums = [5,7,7,8,8,10], target = 6
輸出: [-1,-1]
方法:
二分法解題:
- 因爲題目要求時間複雜度爲:O(log n) ,故需要採用二分法進行查找target在數組中的第一個位置和最後一個位置
- 要注意的時因爲我們初始化 right = nums.length
所以決定了我們的「搜索區間」是 [left, right)
所以決定了 while (left < right)
同時也決定了 left = mid + 1 和 right = mid
詳細代碼:
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = { -1, -1 };
if(nums.length==0) return res;
boolean flag = true;
int leftIndex = boundIndex(nums, target, flag);
//leftIndex == nums.length代表target不存在
if (leftIndex == nums.length||nums[leftIndex] != target)
return res;
res[0] =leftIndex;
res[1] = boundIndex(nums, target, false)-1;
return res;
}
public int boundIndex(int[] nums, int target, boolean flag) {
int low = 0, high = nums.length;
while (low < high) {
int mid = (low + high) / 2;
//遞歸mid左邊的數列
if (target < nums[mid] || (flag &&(target == nums[mid]))) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}