您的位置:首页 > 编程语言 > Java开发

leetcode解题之34. Search for a Range java 版(数字在排序数组中出现的次数)

2017-04-07 14:37 483 查看

34. Search for a Range

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of
O(log n).

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

For example,

Given
[5, 7, 7, 8, 8, 10]
and target value 8,

return
[3, 4]
.

数字在排序数组中出现的次数

类似二分查找,但等于目标值时需要向左向右对其相邻元素进行判断。

非递归

public int[] searchRange(int[] nums, int target) {
int first, last;
// 获取第一个数字为target的下标
first = getFirstKIndex(nums, 0, nums.length - 1, target);
// 获取最后一个数字为target的下标
last = getLastIndex(nums, 0, nums.length - 1, target);
return new int[] { first, last };
}

private int getLastIndex(int[] array, int start, int end, int k) {
int mid;
// 一定要等有=!!!!!!
while (start <= end) {
mid = (start + end) / 2;
if (k == array[mid]) {
// k在中间或者结尾,找到
if (mid == end || array[mid + 1] != k) {
return mid;
} else {
start = mid + 1;
}
} else if (k < array[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}

private int getFirstKIndex(int[] array, int start, int end, int k) {
int mid;
// 一定要等有=!!!!!!
while (start <= end) {
mid = (start + end) / 2;
if (k == array[mid]) {
// k在中间或者开头,找到
if (mid == start || array[mid - 1] != k) {
return mid;
} else {
end = mid - 1;
}
} else if (k < array[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}

递归

public int[] searchRange(int[] A, int target) {
int[] result = new int[2];
result[0] = getBoundRange(A, 0, A.length - 1, target, true);
result[1] = getBoundRange(A, 0, A.length - 1, target, false);
return result;
}

public int getBoundRange(int[] A, int l, int r, int target, boolean left) {
if (l > r)
return -1;
else {
int m = (l + r) / 2;
if (A[m] == target) {
// 根据true或者false判断在左侧还是右侧查找
if (left) {
if (m == 0 || A[m - 1] != target)
return m;
else
return getBoundRange(A, l, m - 1, target, left);
} else {
if (m == A.length - 1 || target != A[m + 1])
return m;
else
return getBoundRange(A, m + 1, r, target, left);
}
} else if (A[m] > target) {
return getBoundRange(A, l, m - 1, target, left);
} else {
return getBoundRange(A, m + 1, r, target, left);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息