Skip to content

Commit 925fd42

Browse files
committed
剑指Offer,数字在排序数组中出现的次数
1 parent 0ffb027 commit 925fd42

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
/**
3+
* 剑指Offer,数字在排序数组中出现的次数
4+
*/
5+
6+
public class NumberAppearanceCountInSortArray {
7+
8+
public static void main(String[] args) {
9+
int[] array = {1, 2, 3, 4, 6, 7, 8};
10+
System.out.println(GetNumberOfK(array, 5));
11+
}
12+
13+
public static int GetNumberOfK(int [] array , int k) {
14+
15+
if (array == null || array.length <= 0) {
16+
return 0;
17+
}
18+
19+
int left = 0;
20+
int right = array.length - 1;
21+
int index = 0;
22+
while (true) {
23+
index = left + (right - left) / 2;
24+
if (array[index] == k || left == right) {
25+
break;
26+
}
27+
if (array[index] > k) {
28+
right = index - 1;
29+
}else {
30+
left = index + 1;
31+
}
32+
}
33+
34+
int cnt = 0;
35+
for (int i = index; i >= 0; i--) {
36+
if (array[i] == k) {
37+
cnt++;
38+
}else {
39+
break;
40+
}
41+
}
42+
43+
for (int i = index + 1; i < array.length; i++) {
44+
if (array[i] == k) {
45+
cnt++;
46+
}else {
47+
break;
48+
}
49+
}
50+
51+
return cnt;
52+
}
53+
}

0 commit comments

Comments
 (0)