标签:
统计一个数字在排序数组中出现的次数。
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int num = 0;
if (array == null || array.length == 0) {
return num;
}
int firstK = getFirstK(array, k, 0, array.length - 1);
int lastK = getLastK(array, k, 0, array.length - 1);
System.out.println("first:" + firstK + " lastK:" + lastK);
if (firstK > -1 && lastK > -1) {
return lastK - firstK + 1;
}
return num;
}
public int getFirstK(int[] data, int k, int start, int end) {
if (start > end) {
return -1;
}
int midIndex = (start + end) / 2;
int midData = data[midIndex];
if (midData == k) {
if ((midIndex > 0 && data[midIndex - 1] != k) || midIndex == 0) {
return midIndex;
} else {
end = midIndex - 1;
}
} else if (midData > k) {
end = midIndex - 1;
} else {
start = midIndex + 1;
}
return getFirstK(data, k, start, end);
}
public int getLastK(int[] data, int k, int start, int end) {
if (start > end) {
return -1;
}
int midIndex = (start + end) / 2;
int midData = data[midIndex];
if (midData == k) {
if ((midIndex < data.length - 1 && data[midIndex + 1] != k) || midIndex == data.length - 1) {
return midIndex;
} else {
start = midIndex + 1;
}
} else if (midData > k) {
end = midIndex - 1;
} else {
start = midIndex + 1;
}
return getLastK(data, k, start, end);
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5656425.html