[LeetCode] 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"

 

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.

 

這道題給了我們一堆有序的字母,然后又給了我們一個target字母,讓我們求字母數組中第一個大於target的字母,數組是循環的,如果沒有,那就返回第一個字母。像這種在有序數組中找數字,二分法簡直不要太適合啊。題目中說了數組至少有兩個元素,那么我們首先用數組的尾元素來跟target比較,如果target大於等於尾元素的話,直接返回數組的首元素即可。否則就利用二分法來做,這里是查找第一個大於目標值的數組,博主之前做過二分法的總結,參見這個帖子LeetCode Binary Search Summary 二分搜索法小結,參見代碼如下:

 

解法一:

class Solution {
public:
    char nextGreatestLetter(vector<char>& letters, char target) {
        if (target >= letters.back()) return letters[0];
        int n = letters.size(), left = 0, right = n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (letters[mid] <= target) left = mid + 1;
            else right = mid;
        }
        return letters[right];
    }
};

 

我們也可以用STL自帶的upper_bound函數來做,這個就是找第一個大於目標值的數字,如果返回end(),說明沒找到,返回首元素即可,參見代碼如下:

 

解法二:

class Solution {
public:
    char nextGreatestLetter(vector<char>& letters, char target) {
        auto it = upper_bound(letters.begin(), letters.end(), target);
        return it == letters.end() ? *letters.begin() : *it;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 [LeetCode] 1095. Find in Mountain Array 山形數組中查找目標值 [LeetCode] 1074. Number of Submatrices That Sum to Target 元素和為目標值的子矩陣數量 [LeetCode] Find K Pairs with Smallest Sums 找和最小的K對數字 Leetcode練習(Python):數組類:第34題:給定一個按照升序排列的整數數組 nums,和一個目標值 target。找出給定目標值在數組中的開始位置和結束位置。 你的算法時間復雜度必須是 O(log n) 級別。 如果數組中不存在目標值,返回 [-1, -1]。 給定一個整數數組 nums 和一個整數目標值 target,請你在該數組中找出 和為目標值 target  的那 兩個 整數,並返回它們的數組下標。 給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數 例如給定nums = [2,7,11,15],target = 9 php 獲取兩個給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。 刷題:給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM