/** * Return the smallest character that is strictly larger than the search character, * If no such character exists, return the smallest character in the array * @param sortedStr : sorted list of letters, sorted in ascending order. * @param c : character for which we are searching. * Given the following inputs we expect the corresponding output: * ['c', 'f', 'j', 'p', 'v'], 'a' => 'c' * ['c', 'f', 'j', 'p', 'v'], 'c' => 'f' * ['c', 'f', 'j', 'p', 'v'], 'k' => 'p' * ['c', 'f', 'j', 'p', 'v'], 'z' => 'c' // The wrap around case * ['c', 'f', 'k'], 'f' => 'k' * ['c', 'f', 'k'], 'c' => 'f' * ['c', 'f', 'k'], 'd' => 'f' */
public class solution{ public static char findNextChar(char [] chs , char target){ int left = 0; int right = chs.length - 1; while(left<=right){ int mid = (left+right)/2; if (chs[mid] == target){ if (mid<chs.length - 1){ while(chs[mid+1]==chs[mid])mid++; return chs[mid+1]; }else{ return chs[0]; } } else if (target > chs[mid]){ left = mid+1; }else{ right = mid -1 ; } } if(left==0)return chs[0]; else if(left==chs.length) return chs[0]; else return chs[left]; //return left == 0? chs[0]:left==chs.length? chs[0]:chs[left]; } public static void main(String[] args) { char[] list = {'c', 'c','f','f', 'f', 'f', 'j', 'j', 'j', 'p', 'p', 'v'}; char[] target = {'a', 'c', 'f', 'k', 'v', 'z'}; for (char c : target) System.out.println(c + " -> " + findNextChar(list, c)); } }output:
a -> cc -> ff -> jk -> pv -> cz -> c
http://www.careercup.com/question?id=5726366532108288
转载于:https://www.cnblogs.com/hygeia/p/5154514.html
相关资源:JAVA上百实例源码以及开源项目