gpt4 book ai didi

java - 计数,数组或 HashMap (或集合)哪个更有效

转载 作者:行者123 更新时间:2023-12-01 14:32:09 26 4
gpt4 key购买 nike

<分区>

假设我们被要求计算并打印给定字符串中每个字符的出现次数。为简单起见,该字符串只有小写字母。我写了这两个函数,我想知道哪个在 Java 中更有效/更可取。

函数一:

private void countAndPrintArray1(String str){
int[] a = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = c - 'a';
a[index] = a[index] + 1;
}

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = a[c -'a'];
System.out.println(c+" -> "+ freq);
}
}

函数二:

    private void countAndPrintArray2(String str){
Map<Character, Integer> map = new HashMap<>();

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.getOrDefault(c, 0) + 1;
map.put(c, freq);
}

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.get(c);
System.out.println(c+" -> "+ freq);
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com