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
    

      

  • 相关阅读:
    error PRJ0019的一个解决心得
    3月3日工作日志88250
    IBM、BEA和JBoss应用服务器采用OSGi
    四级再次挂了
    迁移应用进入基于Annotation MVC的spring 2.5
    如何在VC6.0中设置条件断点
    3月4日工作日志88250
    KMP字符串模式匹配详解
    KMP字符串模式匹配详解
    C/C++之SQLite常用函数
  • 原文地址:https://www.cnblogs.com/apanda009/p/8003716.html
Copyright © 2011-2022 走看看