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
    

      

  • 相关阅读:
    面向对象分析与设计
    数据摘要pandas
    面向对象(简介)
    SQL触发器、事物
    SQL——查询考试
    SQL存储过程、视图
    SQL变量、运算符、分支、循环语句
    SQL连接查询
    SQL主外键和子查询
    SQL各种语句、函数
  • 原文地址:https://www.cnblogs.com/apanda009/p/8003716.html
Copyright © 2011-2022 走看看