zoukankan      html  css  js  c++  java
  • smallest character that is 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' 
    */

     what if the list doesn't contains the result?

    Assuming the list doesn't contain duplicates. It's just a simple variation of binary search.
    
    
    public static char findNextChar(char[] list, char c) {
    		assert list.length > 0;
    		int left = 0, right = list.length - 1;
    		char result = list[0];
    		while (left < right) {
    			int mid = left + (right - left) / 2;
    			if (list[mid] == c) {
    				if (mid < list.length - 1) return list[mid+1];
    				else return result;
    			}
    			else if (list[mid] < c) {
    				left = mid + 1;
    			}
    			else {//list[mid] > c 
    				result = list[mid];
    				right = mid - 1;
    			}
    		}
    		return result;
    	}
    	
    	public static void main(String[] args) {
    		char[] list = {'c', 'f', 'j', 'p', 'v'};
    		char[] target = {'a', 'c', 'f', 'k', 'v', 'z'};
    		for (char c : target) System.out.println(c + " -> " + findNextChar(list, c));
    	}
    Test Case:
    
    
    char[] list = {'c', 'f', 'j', 'p', 'v'};
    Output:
    
    
    a -> c
    c -> f
    f -> j
    k -> p
    v -> c
    z -> c
    

      

  • 相关阅读:
    .NET实现Excel文件的读写 未测试
    权限管理设计
    struts1中配置应用
    POJ 2139 Six Degrees of Cowvin Bacon(floyd)
    POJ 1751 Highways
    POJ 1698 Alice's Chance
    POJ 1018 Communication System
    POJ 1050 To the Max
    POJ 1002 4873279
    POJ 3084 Panic Room
  • 原文地址:https://www.cnblogs.com/apanda009/p/8003716.html
Copyright © 2011-2022 走看看