[LeetCode] Search for a Range (sorted integers array,find start & end position of a target number)
/**
O(n)的解法,从左到右遍历。
**/
public class Solution {
public int[] searchRange(int[] A, int target) {
if(A.length == 0) {
return new int[]{-1,-1};
}
int i = -1, j = -1;
for (int k = 0; k < A.length; k++) {
if(A[k] == target) {
if (i == j && j == -1){ //first time found target
i = k;
j = k;
} else {//second time or later
j = k;
}
}
}
return new int[]{i,j};
}
}
解法2, O(lgN)的解法,二分法
public int[] searchRange(int[] A, int target) {
if (A == null || A.length == 0) return new int[]{-1, -1};
int left = findLeft(A, target);
int right = findRight(A, target);
return new int[]{left, right};
}
private int findLeft(int[] A, int target) {
if (target < A[0] || target > A[A.length-1]) return -1;
if (target == A[0]) return 0;
int start = 0, end = A.length-1;
while (start < end) {
int mid = start + (end - start) >> 1;
if (A[mid] == target && A[mid-1] != target) return mid;
else if (A[mid] < target) start = mid + 1;//go right
else end = mid - 1;
}
return -1;
}
private int findRight(int[] A, int target) {
if (target < A[0] || target > A[A.length-1]) return -1;
if (target == A[A.length-1]) return A.length-1;
int start = 0, end = A.length-1;
while (start < end) {
int mid = start + (end - start) >> 1;
if (A[mid] == target && A[mid+1] != target) return mid;
else if (A[mid] > target) end = mid - 1; //go left
else start = mid + 1;
}
return -1;
}