744. Find Smallest Letter Greater Than Target
class Solution { public char nextGreatestLetter(char[] letters, char target) { // sanity check if(letters[letters.length - 1] <= target ) return letters[0]; int left = 0; int right = letters.length - 1; while(left < right){ int mid = left + (right - left) / 2; if(letters[mid] <= target){ left = mid + 1; }else { right = mid; } } return letters[left]; } }
一开始这个规则没看到,
Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.
把规则都弄清楚后, 还是走例子,
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"
posted on 2018-11-09 10:59 猪猪🐷 阅读(109) 评论(0) 收藏 举报
                    
                
                
            
        
浙公网安备 33010602011771号