199.md 2.1 KB
Newer Older
W
wizardforcel 已提交
1
# 拼图 – 返回所有字符串的第 N 个最长长度
W
wizardforcel 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

> 原文: [https://howtodoinjava.com/puzzles/puzzle-return-all-the-strings-with-the-nth-longest-length/](https://howtodoinjava.com/puzzles/puzzle-return-all-the-strings-with-the-nth-longest-length/)

**算法:**给定一个字符串列表,例如,返回列表中第**个最长长度**的所有字符串:`list – Yuri, Ron, Interview, Longest, List, Contain`**nth = 1** 将返回 只是“ **采访**”,而 **nth = 2** 将返回“ **最长**”和“ **包含**”。

虽然是“如何在 O(n)中长度为 n 的未排序数组中找到第 k 个最大元素”的解决方案? 可以应用于字符串长度,如何转换回以打印所有 n 长度的字符串?

## 解

我编写了一个简单的 Java 程序,该程序可以从字符串列表中找到“所有 N 个最长的元素”。 程序如下:

```java
package com.howtodoinjava.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class NthLogestStringAlgorithm
{
    public static void main(String[] args)
    {
        int n = 0;
        List<String> list = new ArrayList<String>();
        list.add("Yuri");
        list.add("Ron");
        list.add("Interview");
        list.add("Longest");
        list.add("List");
        list.add("Contain");

        System.out.println( findNthLongestElement(list, n) );
    }

    private static List<String> findNthLongestElement(List<String> list, int n)
    {
        if(n < 1) {
            return null; //Handle invalid case
        }

        TreeMap<Integer, List<String>> map = new TreeMap<>();

        for(String str : list)
        {
            Integer length = str.length();
            List<String> tempList = map.get(length) != null ? map.get(length) : new ArrayList<String>();
            tempList.add(str);
            map.put(length, tempList);
        }
        return map.get( map.descendingKeySet().toArray()[n-1] );
    }
}
```

```java
========Output of program=======

n = 0 => null
n = 1 => [Interview]
n = 2 => [Longest, Contain]
n = 3 => [Yuri, List]
n = 4 => [Ron]
```

**祝您学习愉快!**