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 }
  • 相关阅读:
    JavaScript Validator 报错
    JSP项目_Web路径_磁盘物理路径
    TreaponseHeader
    TrequestHeader
    HTML学习笔记1
    SQL文摘:DATE_TRUNC: A SQL Timestamp Function You Can Count On
    SQL文摘:Writing Subqueries in SQL
    Python文摘:Requests (Adavanced Usage)
    Python文摘:Requests
    Python文摘:More About Unicode in Python 2 and 3
  • 原文地址:https://www.cnblogs.com/real1587/p/9807332.html
Copyright © 2011-2022 走看看