[英]Finding the third largest string from an array of strings in Java
我的一個朋友問我關於他們的講師作為練習給他們的編碼挑戰。 我有一個解決方案來解決它。 但我認為解決方案對於一個簡單的分類問題來說太長了。 所以,我想問一下是否有更直接的方法來解決這個挑戰。
有一個函數third_greatest(),它接受一個字符串數組並返回第三大單詞。 因此,例如:如果數組是 ["hello", "world", "before", "noon"],則輸出應該是 "world",因為 "before" 有六個字母長,而 "hello" 和 "world" " 都是 5,但輸出應該是 "world",因為它出現在數組中的最后一個五個字母的單詞。 如果數組是 ["hello", "world", "after", "noon"],輸出應該是 "after" 因為前三個單詞都是五個字母,所以返回最后一個。 該數組將至少包含三個字符串,每個字符串僅包含字母。
我提出的解決方案使用 HashMap 以字典方式存儲字符串。 Hashmap 將以 Integer 和 ArrayList 的形式存儲數據、長度和具有該長度的單詞。 一旦代碼完成了對 String 數組的迭代並將各個字符串放入它們單獨的組中,我就從 Hashmap 中提取了在數組中找到的所有鍵(長度),並按升序對它們進行排序。 之后,Hashmap 的 ArrayList 中的所有值都會被轉移到另一個 ArrayList 中。 最后,它將新 ArrayList 的第三個 String 返回給函數調用者。
謝謝。
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
class Main {
public static void main (String args[]) {
String test[] = {"hello", "world", "before", "noon"};
System.out.println(third_greatest(test));
}
public static String third_greatest(String words[]) {
HashMap<Integer, ArrayList<String>> words_length = new HashMap<Integer, ArrayList<String>>();
for (String word : words) {
int length = word.length();
if (words_length.containsKey(length)) {
words_length.get(length).add(word);
} else {
ArrayList<String> temp = new ArrayList<String>();
temp.add(word);
words_length.put(length, temp);
}
}
Object keys[] = words_length.keySet().toArray();
Integer sorted[] = new Integer[words_length.size()];
for (int x = 0; x < keys.length; x++) {
sorted[x] = (Integer)keys[x];
}
Arrays.sort(sorted);
ArrayList<String> results = new ArrayList<String>();
for (int x = sorted.length - 1; x >= 0; x--) {
ArrayList<String> temp = words_length.get(sorted[x]);
for (String word : temp) {
results.add(word);
}
}
return results.get(2);
}
}
對流按長度的降序排序並跳過前 2 個元素。 需要 Java 11
import java.util.*;
class ThirdLongest
{
public static void main(String[] args) {
String[] words={"Word","Longer Word","Longest Word Here"};
String word=Arrays.stream(words)
.sorted((s1,s2)->Integer.compare(s2.length(),s1.length()))
.skip(2)
.findFirst()
.get();
System.out.println(word);
}
}
或者
只需按降序對數組進行排序並返回第三個元素
Arrays.sort(words,(s1,s2)->Integer.compare(s2.length(),s1.length()));
return words[2];
正如其他人所指出的,簡單的解決方案是根據字符串大小(或任何排序標准)對數組進行排序。 然后從排序列表中取倒數第三個元素。
這是一個O(NlogN)
解決方案,因為排序步驟是O(NlogN)
。
這是一個O(N)
的解決方案。
最后,您將執行O(N)
次測試,並且最多執行 O(N O(N)
次排序的 3 或 4 元素數組。 對於O(N)
的整體復雜性。
可以對排序步驟進行微優化,以避免循環和不必要的數組創建和復制。
注意:如果輸入列表總是很小,那么這個(更復雜的)解決方案不值得努力。 當縮放變量具有較小的值時,具有更好的算法復雜度並不能保證更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.