[英]Find the count of similar elements in two equal-sized arrays using HashMap
[英]Find the count of elements in two char[] arrays?
我必須找到兩個 char[] arrays 中的元素數。這些 arrays 是 char arrays,最大大小為 5,只能使用字母 A 到 G。 我將把它分成兩個 arrays - arr1
和arr0
。 arr1 優先於 arr2,因為如果 arr1 有 3 個'A'
元素而 arr2 有 4 個,則最大計數為 3。
我必須找到這些 arrays 共享的公共元素的數量,其中 arr1 在 maximum count 中具有優先權。 到目前為止我很難過。 我想遍歷字符:
for (char x = 'A'; x <= G; x++) {
//code
}
但是我不知道在那之后該怎么做。 任何幫助,將不勝感激。
這感覺就像家庭作業,所以我不會給你一個完整的解決方案,而是給你一些指導和你需要拆卸/重新組裝才能使其工作的部件,希望這能讓你更好地學習和理解建議的解決方案。
這是一個使用 HashMap 計算字符串中元素的解決方案,您可以輕松地調整它以計算數組中的元素:
// Java prorgam to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
static void characterCount(String inputString)
{
// Creating a HashMap containing char
// as a key and occurrences as a value
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
// Converting given string to char array
char[] strArray = inputString.toCharArray();
// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
// If char is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
}
else {
// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Printing the charCountMap
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
// Driver Code
public static void main(String[] args)
{
String str = "Ajit";
characterCount(str);
}
}
最后,您可以按出現次數排序並獲得最高的出現次數,有很多相關資源,這是 StackOverflow 的示例:
Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());
Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));
for (Person p : peopleByAge) {
System.out.println(p.getName() + "\t" + p.getAge());
}
arr1;
arr2;
int find(char) {
int a = 0;
int b = 0;
for(let i = 0; i < arr1.length; i++) {
if(arr1[i] === char)
a++;
}
for(let j = 0; j < arr2.length; j++) {
if(arr2[j] === char)
b++;
}
if(a > 0){
return a;
} else {
return Math.max(a, b);
}
}
numOccurence = find(char);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.