📜  | |问题 3(1)

📅  最后修改于: 2023-12-03 15:06:08.803000             🧑  作者: Mango

| | 问题 3

简介

| | 问题 3 是一种常见的编程题型,通常涉及到字符串处理、数组操作和逻辑运算。在该问题中,输入一个字符串或数组,需要找到其中出现最多的数字或字母,并输出该数字或字母及其出现次数。

解法
方法一:使用HashMap

使用HashMap是解决该问题的常用方法,具体步骤如下:

  1. 创建一个HashMap,键为唯一的数字或字母,值为数字或字母出现的次数。
  2. 遍历字符串或数组,对于每个数字或字母,更新HashMap中对应的值。
  3. 遍历HashMap,找到出现次数最多的数字或字母,输出其出现次数和值。

该方法的时间复杂度为 O(n),空间复杂度为 O(n)。

方法二:使用桶排序

另一种解决该问题的方法是使用桶排序,具体步骤如下:

  1. 创建一个桶数组,桶的数量为数字或字母的种类数,将每个桶的值初始化为0。
  2. 遍历字符串或数组,对于每个数字或字母,将其对应桶的值加1。
  3. 遍历桶数组,找到出现次数最多的数字或字母,输出其出现次数和对应的数字或字母。

该方法的时间复杂度为 O(n),空间复杂度为 O(k),其中 k 为数字或字母的种类数。

示例代码
Java
public static char findMostCommonChar(String str) {
    HashMap<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    char res = ' ';
    int max = 0;
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        int freq = entry.getValue();
        if (freq > max) {
            max = freq;
            res = entry.getKey();
        }
    }
    return res;
}
Python
def find_most_common_char(s):
    count = [0] * 256
    for c in s:
        count[ord(c)] += 1
    max_count = 0
    res = ' '
    for i in range(256):
        if count[i] > max_count:
            max_count = count[i]
            res = chr(i)
    return res
C++
char findMostCommonChar(string str) {
    vector<int> count(256, 0);
    for (char c : str) {
        count[c]++;
    }
    int max_count = 0;
    char res = ' ';
    for (int i = 0; i < 256; i++) {
        if (count[i] > max_count) {
            max_count = count[i];
            res = i;
        }
    }
    return res;
}

以上代码仅为示例,具体实现可能因语言和场景的不同而有所改变,实际使用时需根据具体情况进行调整。