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"

找数组中比target大的最小元素。

最简单的方法就是从头开始遍历数组,然后返回第一个比target大的数。这样的话,在一些很坏的情况下(比如需要返回最后一个数),时间消耗会很高。

所以要想办法把遍历寻找的范围缩小。也就是尽量增大起点位置。可以用二分法更新起点坐标,直到letters[mid]比target大。

class Solution {
public:
    char nextGreatestLetter(vector<char>& letters, char target) {
        int low = 0;
        int high = letters.size()-1;
        if (letters[high]<=target)
            return letters[0];
        
        int mid = low + (high - low)/2;
        while (letters[mid]<=target) {
            low = mid+1;
            mid = low + (high - low)/2;
        }
        
        for (int i=low; i<=mid; ++i) 
            if (letters[i]>target)
                return letters[i];
    }
};

 

posted @ 2017-12-12 18:29  Zzz...y  阅读(247)  评论(0编辑  收藏  举报