zoukankan      html  css  js  c++  java
  • 744. Find Smallest Letter Greater Than Target

    Given a list of sorted characters letterscontaining only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.

    Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], 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. letters has a length in range [2, 10000].
    2. letters consists of lowercase letters, and contains at least 2 unique letters.
    3. target is a lowercase letter.
    题目是变种版的二分查找,返回值字符数组的索引用取余搞定目标比所有字符大这个问题。
     1 char nextGreatestLetter(char* letters, int lettersSize, char target) {
     2         int low=0, high=lettersSize;
     3         while(low<high){
     4             int mid=low+(high-low)/2;
     5             if(letters[mid]>target)    high=mid;//如果比目标大,就往左边找
     6             else    low=mid+1;               //如果比目标小,就往右边推
     7         }
     8         /*l
     9         因为etters数组索引范围是0-lettersSize-1,当low大于lettersSize-1的情况下,
    10         说明字符数组里面不存在比目标大的字符,此时low==lettersSize,对lettersSize进行取余,
    11         返回字符数组第一个元素。
    12         */
    13         return letters[low%lettersSize];
    14 }
  • 相关阅读:
    Ubuntu20.04本地安装Redash中文版
    ubuntu设置root密码
    qmake设置生成文件分类
    QML对象的构造函数和析构函数
    QString使用split按照某字符进行分解
    Qt的qDebug直接打印不添加头文件
    C++宏定义中的#
    Qt设置生成的文件路径
    QWidget禁止最大化
    js-去掉回车和空格
  • 原文地址:https://www.cnblogs.com/real1587/p/9807332.html
Copyright © 2011-2022 走看看