您的位置:首页 > 其它

LeetCode: Search for a Range 解题报告

2014-10-24 12:40 330 查看
[b][b]

public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ret = {-1, -1};

if (A == null || A.length == 0) {
return ret;
}

int len = A.length;
int left = 0;
int right = len - 1;

// so when loop end, there will be 2 elements in the array.
// search the left bound.
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (target == A[mid]) {
// 如果相等,继续往左寻找边界
right = mid;
} else if (target > A[mid]) {
// move right;
left = mid;
} else {
right = mid;
}
}

if (A[left] == target) {
ret[0] = left;
} else if (A[right] == target) {
ret[0] = right;
} else {
return ret;
}

left = 0;
right = len - 1;
// so when loop end, there will be 2 elements in the array.
// search the right bound.
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (target == A[mid]) {
// 如果相等,继续往右寻找右边界
left = mid;
} else if (target > A[mid]) {
// move right;
left = mid;
} else {
right = mid;
}
}

if (A[right] == target) {
ret[1] = right;
} else if (A[left] == target) {
ret[1] = left;
} else {
return ret;
}

return ret;
}
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/divide2/SearchRange.java

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: