• 744. Find Smallest Letter Greater Than Target


    Given a list of sorted characters letters containing 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"
    找到数组里边的大于目标的最小值
    思路如下,用二分查找找到目标即可,如果找不到则返回数组的第一位
    public char nextGreatestLetter(char[] letters, char target) {
            int lo = 0, hi = letters.length;
            while (lo < hi) {
                int mi = lo + (hi - lo) / 2;
                if (letters[mi] <= target) lo = mi + 1;
                else hi = mi;
            }
            return letters[lo % letters.length];
        }

    取mod是因为如果找不到lo最后会变成hi即letters.length

    这种情况下还是返回第一个

  • 相关阅读:
    Office 转 PDF & PDF 转 SWF Windows版
    Office 转 PDF & PDF 转 SWF Linux版
    MP4Box 编译 和相应命令
    CentOS VNC 安装与配置,方便进行运程桌面连接
    系统时钟&&硬件时钟
    IPtables中SNAT、DNAT和MASQUERADE的含义
    配置SNAT实现共享上网
    DNAT & SNAT
    linux应急操作
    linux-清理linux空间
  • 原文地址:https://www.cnblogs.com/icysnow/p/8268882.html
Copyright © 2020-2023  润新知