2024/11/11 灵茶题单 二分查找
This commit is contained in:
parent
d2ad6fb2c4
commit
0dc0b10835
|
@ -0,0 +1,35 @@
|
||||||
|
package com.cool.ling_cha_mount.binary_search;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author : Cool
|
||||||
|
* @date: 2024/11/11
|
||||||
|
*/
|
||||||
|
public class Num744 {
|
||||||
|
public char nextGreatestLetter(char[] letters, char target) {
|
||||||
|
int index=binarySearch(letters,(char)((int)target+1));
|
||||||
|
if(index<letters.length){
|
||||||
|
return letters[index];
|
||||||
|
}
|
||||||
|
return letters[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
private int binarySearch(char[] letters,char target){
|
||||||
|
int left=0;
|
||||||
|
int right=letters.length-1;
|
||||||
|
while(left<=right){
|
||||||
|
int mid=(right-left)/2+left;
|
||||||
|
if(letters[mid]>=target){
|
||||||
|
right=mid-1;
|
||||||
|
}else{
|
||||||
|
left=mid+1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void test(){
|
||||||
|
nextGreatestLetter(new char[]{'c','f','j'},'c');
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue