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);
}
}
}
相关文章推荐
- 【剑指offer-解题系列(38)】数字在排序数组中出现的次数
- 剑指offer(34)-数字在排序数组中出现的次数
- 34、数字在排序数组中出现的次数t
- [Python]数字在排序数组中出现的次数 解题思路
- 在排序数组中,找出给定数字的出现次数
- 在排序数组中,找出给定数字出现的次数。比如【1,2,2,2,3】中2的出现次数为3次
- 数字在排序数组中出现的次数
- 10、在排序数组中,找出给定数字出现的次数
- 九度笔记之 1349:数字在排序数组中出现的次数
- 数字在排序数组中出现的次数
- 数字在排序数组中出现的次数——离线查询
- 面试题32:数字在排序数组中出现的次数
- 消除原理____假设数组中有一个数字出现的次数超过了数组长度的一半,试编程找出这个数字(qosrt 快速排序 哈希)
- 数字在排序数组中出现的次数
- 在排序数组中,找出给定数字的出现次数
- 【剑指offer】数字在排序数组中出现的次数
- 在排序数组中,找出给定数字的出现次数
- 数字在排序数组中出现的次数
- 数字在排序数组中出现的次数
- 假设数组中有一个数字出现的次数超过了数组长度的一半,试编程找出这个数字(消除 qosrt 快速排序 哈希)