• 744. Find Smallest Letter Greater Than Target


    问题:

    给定一个升序字符数组。

    求比给定target字符大的,最小的字符。(假设给定字符数组是循环的,即第一个字符>最后一个字符)

    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:
    letters has a length in range [2, 10000].
    letters consists of lowercase letters, and contains at least 2 unique letters.
    target is a lowercase letter.
    

      

    解法:二分查找(Binary Search)

    在给定字符数组letters中,找到第一个>target字符的字符。

    ⚠️ 注意:(字符数组是循环:)若未找到,则返回letters[0]

    代码参考:

     1 class Solution {
     2 public:
     3     char nextGreatestLetter(vector<char>& letters, char target) {
     4         int l = 0, r = letters.size();
     5         while(l<r) {
     6             int m = l+(r-l)/2;
     7             if(letters[m]>target) {//找到第一个>target
     8                 r = m;
     9             } else {
    10                 l = m+1;
    11             }
    12         }
    13         return (l==letters.size())?letters[0]:letters[l];
    14     }
    15 };
  • 相关阅读:
    HDOJ 1284 钱币兑换问题
    WA : csu1019 simple line editor
    HDOJ1232 并查集
    最长回文子串
    Where's Waldorf?
    csu 1148 词典
    csu 1011 Counting Pixels
    Product:java高精度乘法
    内置类型开方
    csu 1019 Simple Line Editor
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13512244.html
Copyright © 2020-2023  润新知