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 条评论
登录 后参与评论

相关文章

来自专栏格子的个人博客

Java源码阅读之ArrayList - JDK1.8

当你对某件事情很感兴趣的时候,时间的流逝在感知中都模糊了(是不是很文艺,绕口得都快听不懂了),通俗来说,就是时间过得很快。

815
来自专栏ml

HDUOJ---The Moving Points

The Moving Points Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/...

3114
来自专栏令仔很忙

集合详解(二)----ArrayList源代码剖析(JDK1.7)

ArrayList是List类的一个典型的实现,是基于数组实现的List类,因此,ArrayList封装了一个动态的、可变长度的Object[]数组。Arra...

481
来自专栏开发 & 算法杂谈

PAT Advanced 1005

Given a non-negative integer N, your task is to compute the sum of all the digi...

702
来自专栏cmazxiaoma的架构师之路

Java数据结构和算法(1)--自定义一个数组类和动态数组类

1194
来自专栏机器学习入门

LWC 53:693. Binary Number with Alternating Bits

LWC 53:693. Binary Number with Alternating Bits 传送门:693. Binary Number with Alte...

1998
来自专栏机器学习入门

LWC 60:736. Parse Lisp Expression

LWC 60:736. Parse Lisp Expression 传送门:736. Parse Lisp Expression Problem: You a...

1687
来自专栏WD学习记录

Leetcode Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matchi...

652
来自专栏计算机视觉与深度学习基础

Leetcode 124 Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. For this problem, a path is de...

1949
来自专栏ml

poj------2406 Power Strings

A - Power Strings 难度:☆☆ Time Limit:3000MS     Memory Limit:65536KB     64bit I...

2978

扫码关注云+社区