Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
class Solution {
// [5, 7, 7, 8, 8, 10]
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
var startIndex = 0;
var endIndex = nums.count - 1;
while(startIndex <= endIndex) {
let midIndex = startIndex + (endIndex - startIndex)/2;
let startValue = nums[startIndex];
let midValue = nums[midIndex];
let endValue = nums[endIndex];
if(midValue == target) {
return self.findIndexs(nums, target, midIndex);
break;
}
if(target > midValue) {
startIndex = midIndex + 1;
}
else {
endIndex = midIndex - 1;
}
}
return [-1, -1];
}
func findIndexs(_ nums: [Int], _ target: Int, _ inputIndex: Int) -> [Int] {
var result:[Int] = []
var startIndex = inputIndex;
var endIndex = inputIndex;
while ((startIndex - 1) >= 0 && nums[startIndex - 1] == target) {
startIndex -= 1;
}
while ((endIndex + 1) < nums.count && nums[endIndex + 1] == target) {
endIndex += 1;
}
result.append(startIndex);
result.append(endIndex);
return result;
}
}