[英]Reducing time complexity in a nested loop?
就目前而言,有幾種方法可以降低嵌套循環中的時間復雜度。 在一個特定的示例中,我正在考慮查找最大數量、重復元素和排序列表。 但是,我不確定嵌套循環中這些場景的最佳方法:
public static void main(String[] args) {
List<Integer> list = List.of(2, 4, 6, 8, 10, 4, 4, 15, 6, 9, 6);
findMultiple(list);
}
private static void findMultiple(List<Integer> list) {
int size = list.size();
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < size; i++) {
// assigning map by using list values as key or value ???
}
System.out.println(Arrays.toString(result));
}
通常我在經典示例中需要 2 個循環,但使用HashMap
可以將其減少為單個循環。
1.我如何使用 HashMap 來找到這個例子的多個元素?
2.除了 HashMap 之外,執行此操作的最佳方法是什么?
一般來說,對於此類任務,我總是建議您使用Streams而不是迭代解決方案(即循環)。 它們高效且編寫緊湊。
List<Integer> list = List.of(2, 4, 6, 8, 10, 4, 4, 15, 6, 9, 6);
List<Integer> sortedWithoutDuplicates = list.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
Set<Integer> uniqueItems = new HashSet<>();
Set<Integer> sortedDuplicates = list.stream()
.filter(n -> !uniqueItems.add(n)) // !items.add(n) = false if the element was already in the set.
.sorted()
.collect(Collectors.toSet());
Optional<Integer> max = list.stream().max(Integer::compareTo);
// output
System.out.printf("list: %s\n", list.stream().map(String::valueOf).collect(Collectors.joining(",")));
System.out.printf("sorted without duplicates: %s\n", sortedWithoutDuplicates.stream().map(String::valueOf).collect(Collectors.joining(",")));
System.out.printf("sorted duplicates: %s\n", sortedDuplicates.stream().map(String::valueOf).collect(Collectors.joining(",")));
max.ifPresent(integer -> System.out.printf("max: %d\n", integer));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.