• 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 }
  • 相关阅读:
    Go jaegerde 应用【logger+gorm+grpc+http】
    Go gRPC 调试工具
    iris和xxl-job整合
    Go Grpc部署到 k8s【端口共享】
    rocketmq事务 go 采用rocketmq-client-go的实现
    Go Grpc部署到 k8s【负载均衡】
    ubuntu18安装Kubernetes 1.20.5
    k8s Python API
    go nacos服务发现
    k8s集群日志收集ELK和graylog
  • 原文地址:https://www.cnblogs.com/real1587/p/9807332.html
Copyright © 2020-2023  润新知