如何检查多维数组中是否存在重复数字?含3x3数组函数需求
Hey there! For your university project, checking duplicates in a 3x3 multidimensional array is straightforward once you break down the problem. Let's walk through the approach and implement it step by step.
核心思路
The key idea here is to flatten the 2D array into a 1D list (since checking duplicates in a single list is much simpler). Once we have all elements in one place, we can either:
- Use a set (which automatically removes duplicates) and compare its length to the original flattened list, or
- Manually track seen elements as we iterate through the array, returning early if we find a duplicate.
Python实现(两种方法)
方法1:利用集合快速检查
This is the most concise approach, perfect for clean code:
def has_duplicates(grid): # 将3x3网格扁平化为一维列表 flat_list = [num for row in grid for num in row] # 如果集合长度小于原列表,说明存在重复 return len(flat_list) != len(set(flat_list))
方法2:手动遍历检查(适合理解底层逻辑)
If your course wants you to demonstrate a deeper understanding of iteration and tracking, this method stops as soon as a duplicate is found (more efficient in cases where duplicates appear early):
def has_duplicates_manual(grid): seen_elements = [] for row in grid: for num in row: if num in seen_elements: # 找到重复项,立即返回结果 return True seen_elements.append(num) # 遍历结束未发现重复 return False
测试示例
Let's test both functions with sample grids:
# 包含重复项的网格(数字1出现两次) duplicate_grid = [ [1, 2, 3], [4, 5, 1], [6, 7, 8] ] # 无重复项的网格 unique_grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(has_duplicates(duplicate_grid)) # 输出: True print(has_duplicates(unique_grid)) # 输出: False print(has_duplicates_manual(duplicate_grid)) # 输出: True print(has_duplicates_manual(unique_grid)) # 输出: False
C语言实现(适合底层编程课程)
If your project uses C, here's a straightforward implementation that follows the same manual tracking logic:
#include <stdbool.h> #include <stdio.h> bool hasDuplicates(int grid[3][3]) { int seen[9]; int count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int current = grid[i][j]; // 检查当前数字是否已在seen数组中 for (int k = 0; k < count; k++) { if (seen[k] == current) { return true; } } seen[count++] = current; } } return false; } // 测试函数 int main() { int grid_with_duplicates[3][3] = {{1,2,3}, {4,5,1}, {6,7,8}}; printf("Has duplicates? %d\n", hasDuplicates(grid_with_duplicates)); // 输出: 1 (true) int grid_unique[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; printf("Has duplicates? %d\n", hasDuplicates(grid_unique)); // 输出: 0 (false) return 0; }
注意事项
- 确保输入网格仅包含数值类型(大学项目通常会有这个前提)。如果存在非数值输入的可能,可以在处理前添加类型检查逻辑。
- 对于更大的多维数组,基于集合或哈希表的方法会比嵌套循环更高效,但对于3x3网格来说,以上任意一种方法都能完美胜任。
内容的提问来源于stack exchange,提问作者John Bassem

