劍指offer程式設計題(JAVA實現)——第37題:數字在排序陣列中出現的次數
阿新 • • 發佈:2018-12-27
github | https://github.com/JasonZhangCauc/JZOffer |
---|
- 劍指offer程式設計題(JAVA實現)——第37題:數字在排序陣列中出現的次數
- 題目描述
- 統計一個數字在排序陣列中出現的次數。
public class Test37 {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 5, 5 };
System. out.println(GetNumberOfK(array, 5));
}
public static int GetNumberOfK(int[] array, int k) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == k) {
for (int j = i; j < array.length; j++) {
if (array[j] == k) {
count++;
} else {
break;
}
}
break;
}
}
return count;
}
}
//二分方法
/**
public class Solution {
public int GetNumberOfK(int [] array , int k) {
int length = array.length;
if(length == 0){
return 0;
}
int firstK = getFirstK(array, k, 0, length-1);
int lastK = getLastK(array, k, 0, length-1);
if(firstK != -1 && lastK != -1){
return lastK - firstK + 1;
}
return 0;
}
//遞迴寫法
private int getFirstK(int [] array , int k, int start, int end){
if(start > end){
return -1;
}
int mid = (start + end) >> 1;
if(array[mid] > k){
return getFirstK(array, k, start, mid-1);
}else if (array[mid] < k){
return getFirstK(array, k, mid+1, end);
}else if(mid-1 >=0 && array[mid-1] == k){
return getFirstK(array, k, start, mid-1);
}else{
return mid;
}
}
//迴圈寫法
private int getLastK(int [] array , int k, int start, int end){
int length = array.length;
int mid = (start + end) >> 1;
while(start <= end){
if(array[mid] > k){
end = mid-1;
}else if(array[mid] < k){
start = mid+1;
}else if(mid+1 < length && array[mid+1] == k){
start = mid+1;
}else{
return mid;
}
mid = (start + end) >> 1;
}
return -1;
}
}
*/