Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复Exercise 1.1.29当给定的键值不存在于数组时的问题 #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 60 additions & 19 deletions src/com/jimmysun/algorithms/chapter1_1/Ex29.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,78 @@

public class Ex29 {
public static int rank(int key, int[] a) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == key) {
while (mid >= 0 && a[mid] == key){
mid--;
int lo = 0;
int hi = a.length - 1;

while (hi >= lo) {
int mid = lo + (hi - lo) / 2;
if (a[mid] >= key) {
if (mid == 0) {
return 0;
}
if (a[mid - 1] < key) {
return mid;
} else {
hi = mid - 1;
}
} else {
if (mid == a.length - 1) {
return a.length;
}

if (a[mid + 1] >= key) {
return mid + 1;
} else {
lo = mid + 1;
}
return ++mid;
} else if (a[mid] < key){
low = mid + 1;
} else if (a[mid] > key){
high =mid - 1;
}
}
return -1;

return 0;
}

public static int count(int key, int[] a) {
int num = 1;
int pos = rank(key, a);
while (pos < a.length - 1 && a[pos] == a[++pos]) {
num++;
int rank = rank(key, a);

if (rank == a.length || key != a[rank]) {
return 0;
}
return num;

int lo = rank;
int hi = a.length - 1;
int lastIndex = 0;

while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] > key) {
hi = mid - 1;
} else if (a[mid] < key) {
lo = mid + 1;
} else if (a[mid] == key) {
if (mid == a.length - 1) {
lastIndex = a.length - 1;
break;
}

if (a[mid + 1] > key) {
lastIndex = mid;
break;
} else {
lo = mid + 1;
}
}
}

return lastIndex - rank + 1;
}

public static void main(String[] args) {
int[] a = new int[] {84, 48, 68, 10, 18, 98, 12, 23, 54, 57, 33, 16, 77, 11, 29, 11, 29, 77, 77};
int[] a = new int[] { 84, 48, 68, 10, 18, 98, 12, 23, 54, 57, 33, 16, 77, 11, 29, 11, 29, 77, 77 };
Arrays.sort(a);
System.out.println(rank(29, a));
System.out.println(count(48, a));
// test the condition that the key not exist in the array
System.out.println(rank(14, a));
System.out.println(count(14, a));
}
}