[LintCode/LeetCode] Search for a Range [左右邊界法/一次迴圈法]

NO IMAGE

Problem

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1]

Another Binary Search Method

public class Solution {
public int[] searchRange(int[] nums, int target) {
int n = nums.length;
int[] res = {-1, -1};
int start = 0, end = n-1;
while (nums[start] < nums[end]) {
int mid = start   (end - start) / 2;
if (nums[mid] > target) end = mid - 1;
else if (nums[mid] < target) start = mid   1;
else {
if (nums[start] < target) start  ;
if (nums[end] > target) end--;
}
}
if (nums[start] == target) {
res[0] = start;
res[1] = end;
}
return res;
}
}