zoukankan      html  css  js  c++  java
  • [leetcode]744. Find Smallest Letter Greater Than Target大于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"

    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.

    题意

    Solution1

    code

     1 class Solution {
     2     public char nextGreatestLetter(char[] letters, char target) {
     3         
     4         if (letters[0] > target) return letters[0];
     5         if (letters[letters.length - 1] <= target) return letters[0];
     6         
     7         int left = 0;
     8         int right = letters.length - 1;
     9         while (left <= right) {
    10             int mid = left + (right - left) / 2;
    11             if (letters[mid] <= target) {
    12                 left = mid + 1;
    13             }
    14             else if (letters[mid] > target) {
    15                 right = mid - 1;
    16             }
    17         }
    18         return letters[left];    
    19     }
    20 }
  • 相关阅读:
    快速排序的分析与优化
    矩阵原地转置
    变位词问题
    一维向量旋转算法
    位图排序
    Linux网络编程:UDP实现可靠的文件传输
    Linux网络编程:UDP Socket编程范例
    es6+最佳入门实践(6)
    es6+最佳入门实践(5)
    es6+最佳入门实践(4)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10823265.html
Copyright © 2011-2022 走看看