• *Smallest Character strictly larger than the Search Character


    /** 
    * 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 -> c
    c -> f
    f -> j
    k -> p
    v -> c
    z -> c

    http://www.careercup.com/question?id=5726366532108288

  • 相关阅读:
    正则表达式
    数组去重
    [WOJ4354] 蜀石经
    [NOI2002] 银河英雄传说
    [洛谷P2186] 小Z的栈函数
    [洛谷P2756]飞行员配对方案问题
    [洛谷P2071] 座位安排
    [洛谷P2417]课程
    [洛谷P1640] [SCOI2010]连续攻击游戏
    [洛谷P3512 [POI2010]PIL-Pilots]
  • 原文地址:https://www.cnblogs.com/hygeia/p/5154514.html
Copyright © 2020-2023  润新知