在现代编程中,算法和数据结构是程序员必备的技能之一。在这篇文章中,我们将讨论一种经典的编程题目——“数大雁”,并提供Java、Python、JavaScript、C++和C语言的代码示例。这个题目考察的是如何快速、有效地处理数据问题,以解决特定的任务。
题目描述
“数大雁”的题目可以描述为:有一群大雁在飞行中,给定它们的飞行高度,我们需要计算出在某一次飞行中,高度相同的大雁数量。这个问题可以通过使用哈希表来有效地解决。
解题思路
- 数据读取:输入一系列的飞行高度数据。
- 使用哈希表(字典):计数每种高度的出现次数。
- 输出结果:最后将每种高度及其计数输出。
代码示例
以下是用不同编程语言实现的解决方案:
1. Python 实现
def count_geese(heights):
height_count = {}
for height in heights:
if height in height_count:
height_count[height] += 1
else:
height_count[height] = 1
return height_count
# 示例
heights = [20, 10, 20, 30, 10, 20]
result = count_geese(heights)
print(result) # 输出 {20: 3, 10: 2, 30: 1}
2. Java 实现
import java.util.HashMap;
public class GooseCounter {
public static HashMap<Integer, Integer> countGeese(int[] heights) {
HashMap<Integer, Integer> heightCount = new HashMap<>();
for (int height : heights) {
heightCount.put(height, heightCount.getOrDefault(height, 0) + 1);
}
return heightCount;
}
public static void main(String[] args) {
int[] heights = {20, 10, 20, 30, 10, 20};
HashMap<Integer, Integer> result = countGeese(heights);
System.out.println(result); // 输出 {10=2, 20=3, 30=1}
}
}
3. JavaScript 实现
function countGeese(heights) {
const heightCount = {};
heights.forEach(height => {
heightCount[height] = (heightCount[height] || 0) + 1;
});
return heightCount;
}
// 示例
const heights = [20, 10, 20, 30, 10, 20];
const result = countGeese(heights);
console.log(result); // 输出 { '10': 2, '20': 3, '30': 1 }
4. C++ 实现
#include <iostream>
#include <unordered_map>
#include <vector>
std::unordered_map<int, int> countGeese(const std::vector<int>& heights) {
std::unordered_map<int, int> heightCount;
for (int height : heights) {
heightCount[height]++;
}
return heightCount;
}
int main() {
std::vector<int> heights = {20, 10, 20, 30, 10, 20};
auto result = countGeese(heights);
for (const auto& pair : result) {
std::cout << pair.first << ": " << pair.second << std::endl; // 输出高度与数量
}
return 0;
}
5. C 实现
#include <stdio.h>
#include <stdlib.h>
#define MAX_HEIGHT 100
void countGeese(int heights[], int n) {
int heightCount[MAX_HEIGHT] = {0};
for (int i = 0; i < n; i++) {
heightCount[heights[i]]++;
}
for (int i = 0; i < MAX_HEIGHT; i++) {
if (heightCount[i] > 0) {
printf("Height %d: %d\n", i, heightCount[i]); // 输出高度与数量
}
}
}
int main() {
int heights[] = {20, 10, 20, 30, 10, 20};
int n = sizeof(heights) / sizeof(heights[0]);
countGeese(heights, n);
return 0;
}
总结
“数大雁”是一个通过哈希表(字典)来计数重复项的经典问题。在不同的编程语言中实现这一问题展示了数据结构的通用性及其在解决实际问题中的重要性。通过以上示例,我们不仅学习了如何在不同语言中实现相似的逻辑,同时也提高了我们解决实际问题的能力。希望这些实例能对你们的学习和编程有所帮助!