[?]*Smallest Character strictly larger than the Search Character

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[?]*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‘ 
*/

好像有bug

import java.awt.List;
import java.util.ArrayList;
public class solution{

public static char findNextChar(char[] list, char c) {
                if (list == null || list.length == 0)
            throw new IllegalArgumentException("Null or empty list!");
        int start = 0;
        int end = list.length - 1;
        if (c < list[0] || c >= list[list.length - 1])
            return list[0];
        while (start < end) {
            int mid = (start + end) / 2;
            if (c == list[mid]) {
                if (list[mid + 1] > c)
                    return list[mid + 1];
                else 
                    start = mid + 1;
            }
            else if (c < list[mid]) {
                end = mid - 1;
            }
            else
                start = mid + 1;
        }
        if (list[start] == c)
            return list[start + 1];
        return list[start];
    }
    
    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));
    }
}

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

以上是关于[?]*Smallest Character strictly larger than the Search Character的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 20. Valid Parentheses

lc 632. Smallest Range

选择排序

POJ 2718 Smallest Difference

选择排序

908. Smallest Range I