LWC 62:744. Find Smallest Letter Greater Than Target

LWC 62:744. Find Smallest Letter Greater Than Target

传送门:744. Find Smallest Letter Greater Than Target

Problem:

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:

letters has a length in range [2, 10000].

letters consists of lowercase letters, and contains at least 2 unique letters.

target is a lowercase letter.

思路: 因为wrap around,所以当给的target大于最大元素,就取集合中最小字符。否则,取大于target的第一个元素。(集合需要排序)

Java版:

    public char nextGreatestLetter(char[] letters, char target) {
        Set<Character> set = new HashSet<>();
        for (char c : letters) set.add(c);

        char[] let = new char[set.size()];
        int i = 0;
        for (char c : set) {
            let[i++] = c;
        }

        Arrays.sort(let);
        for (int j = 0; j < let.length; ++j) {
            if (let[j] > target) return let[j];
        }
        return let[0];
    }

实际上是不需要去重的,代码如下:

    public char nextGreatestLetter(char[] letters, char target) {
        Arrays.sort(letters);
        for (int j = 0; j < letters.length; ++j) {
            if (letters[j] > target) return letters[j];
        }
        return letters[0];
    }

因为集合有序,所以可以使用upper_bound的二分查找,代码如下:

    public char nextGreatestLetter(char[] letters, char target) {
        Arrays.sort(letters);
        return letters[upperBound(letters, target)];
    }

    public int upperBound(char[] letters, char target) {
        int l = 0;
        int r = letters.length - 1;
        while (l < r) {
            int m = l + (r - l) / 2;
            if (letters[m] <= target) {
                l = m + 1;
            }
            else{
                r = m;
            }
        }
        if (letters[r] > target) return r;
        else return 0;
    }

当然你也可以使用Java自家的二分查找接口,但可惜的是,官方接口不支持重复元素集合的准确查找(会出错),所以在使用之前需要对元素去重。

代码如下:

    public char nextGreatestLetter(char[] letters, char target) {
        Set<Character> set = new HashSet<>();
        for (char c : letters) set.add(c);

        char[] let = new char[set.size()];
        int i = 0;
        for (char c : set) {
            let[i++] = c;
        }

        Arrays.sort(let);
        int idx = Arrays.binarySearch(let, target);
        if (idx >= 0){
            if (idx + 1 >= let.length) return let[0];
            else return let[idx + 1];
        }
        else {
            idx = -idx - 1;
            if (idx == let.length) return let[0];
            else return let[idx];
        }
    }

Python版本:

    def nextGreatestLetter(self, letters, target):
        """
        :type letters: List[str]
        :type target: str
        :rtype: str
        """
        sorted(letters)
        for l in letters:
            if (target < l): return l
        return letters[0]

自带的库也是非常方便:

    def nextGreatestLetter(self, letters, target):
        """
        :type letters: List[str]
        :type target: str
        :rtype: str
        """
        pos = bisect.bisect_right(letters, target)
        return letters[0] if pos == len(letters) else letters[pos] 

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏C语言及其他语言

【每日一题】 问题 1233: 核电站问题

一个核电站有N个放核物质的坑,坑排列在一条直线上。如果连续3个坑中放入核物质,则会发生爆炸,于是,在某些坑中可能不放核物质。现在,请你计算:对于给定的N,求不发...

912
来自专栏小樱的经验随笔

HDU 1250 Hat's Fibonacci

Hat's Fibonacci Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32...

34011
来自专栏从流域到海域

《数据结构》 循环链表和双向链表常用操作代码集合

Ps:每段代码中,添加了署名Solo的代码为博主本人所写,其余来自课本或者老师。 大量操作等同于单链表。重复的操作不再贴出,可以查看之前的博文。 循环链表 //...

1707
来自专栏机器学习入门

LWC 58:724. Find Pivot Index

LWC 58:724. Find Pivot Index 传送门:724. Find Pivot Index Problem: Given an array ...

1798
来自专栏算法修养

Pat 1052 Linked List Sorting (25)

1052. Linked List Sorting (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000...

2586
来自专栏calmound

Farm Irrigation

题意:判断图中的图形有几个集合。         这道题做的郁闷死我了,为了找开始字母的错误一个一个匹对。         这道题让我也懂得了表格的位置可以代表...

2534
来自专栏小樱的经验随笔

Codeforces 810C Do you want a date?(数学,前缀和)

C. Do you want a date? time limit per test:2 seconds memory limit per test:256 m...

2515
来自专栏海天一树

小朋友学奥数(21):康托展开

把一个整数X展开成如下形式: X = an * (n - 1)! + an-1 * (n - 2)! + … + ai * (i - 1)! + … + a2 ...

614
来自专栏King_3的技术专栏

leetcode-680-Valid Palindrome II

1685
来自专栏wym

Educational Codeforces Round 44 (Rated for Div. 2)A. Chess Placing

You are given a chessboard of size 1 × n. It is guaranteed that n is even. The c...

842

扫码关注云+社区