744. Find Smallest letter Greater Than Target

Source: Internet
Author: User

Given a list of sorted characters letters containing only lowercase letters, and Given a target letter target , find the Smalle St element in the list is larger than the given target.

Letters also wrap around. For example, if the target was target = ‘z‘ letters = [‘a‘, ‘b‘] and, the answer is ‘a‘ .

Examples:

Input:letters = ["C", "F", "j"]target = "a" output: "c" input:letters = ["C", "F", "j"]target = "C" Output: "F" input:letters = ["C", "F", "j"]target = "D" Output: "f" input:letters = ["C", "F", "j"]target = "g" Output: "j" input:letters = ["C", "F", " J "]target =" J "Output:" c "input:letters = [" C "," F "," j "]target =" K "Output:" C "

Note:

    1. lettersHave a length in range [2, 10000] .
    2. lettersConsists of lowercase letters, and contains at least 2 unique letters.
    3. targetis a lowercase letter.

The topic is a variant version of the binary lookup, the index of the returned value character array with the sizes to get rid of the target than all the characters.
1 CharNextgreatestletter (Char* Letters,intLetterssize,Chartarget) {2         intlow=0, high=letterssize;3          while(low<High ) {4             intmid=low+ (high-low)/2;5             if(Letters[mid]>target) High=mid;//if it's bigger than the target, go to the left.6             ElseLow=mid+1;//if it's smaller than the target, push it to the right.7         }8         /*L9 because the Etters array index range is 0-letterssize-1, when Low is greater than lettersSize-1,Ten Description Character Array there is no larger than the target character, at this time low==letterssize, the letterssize to take the remainder, One returns the first element of a character array.  A         */ -         returnletters[low%Letterssize]; -}

744. Find Smallest letter Greater Than Target

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.