如何获取数组中最大、最小值的所有位置?现有代码存在问题
Hey there! Let's break down why your original code only returns the last position of the max and min values, then fix it to capture every matching index.
First, the problem with your original code:
- You're using single variables
kandlto store indices. Every time you find a value equal to (or larger/smaller than) the current max/min, you overwrite the existing index in that variable. That's why you end up with only the last occurrence instead of all matching positions.
To fix this, we need to collect all indices that match the max and min values, not just overwrite the last one. Here are two straightforward approaches:
Approach 1: Two-Pass Solution (Simple for Small Arrays)
First, we find the actual max and min values in the array. Then we loop through the array again to print every index where the value matches the max or min.
#include <stdio.h> int main() { int A[5] = {2, 2, 1, 4, 1}; int max = A[0], min = A[0]; int i; // First pass: Find the max and min values for (i = 0; i < 5; i++) { if (A[i] > max) max = A[i]; if (A[i] < min) min = A[i]; } // Print all max positions printf("densely (max positions): "); for (i = 0; i < 5; i++) { if (A[i] == max) printf("%d ", i); } printf("\n"); // Print all min positions printf("loosely (min positions): "); for (i = 0; i < 5; i++) { if (A[i] == min) printf("%d ", i); } printf("\n"); return 0; }
This will output:
densely (max positions): 3 loosely (min positions): 2 4
Approach 2: Single-Pass Solution (More Efficient)
If you want to do it in one loop (better for larger arrays), we can use arrays to store all matching indices and track how many we've collected.
#include <stdio.h> #define ARRAY_LEN 5 int main() { int A[ARRAY_LEN] = {2, 2, 1, 4, 1}; int max = A[0], min = A[0]; int max_indices[ARRAY_LEN], min_indices[ARRAY_LEN]; int max_count = 0, min_count = 0; int i; for (i = 0; i < ARRAY_LEN; i++) { // Handle max values if (A[i] > max) { // Found a new max: reset and store current index max = A[i]; max_count = 0; max_indices[max_count++] = i; } else if (A[i] == max) { // Match current max: add index to list max_indices[max_count++] = i; } // Handle min values if (A[i] < min) { // Found a new min: reset and store current index min = A[i]; min_count = 0; min_indices[min_count++] = i; } else if (A[i] == min) { // Match current min: add index to list min_indices[min_count++] = i; } } // Print max positions printf("densely (max positions): "); for (i = 0; i < max_count; i++) { printf("%d ", max_indices[i]); } printf("\n"); // Print min positions printf("loosely (min positions): "); for (i = 0; i < min_count; i++) { printf("%d ", min_indices[i]); } printf("\n"); return 0; }
Key Takeaway
The core issue with your original code was using single variables to track indices—this overwrites previous matches. By collecting all indices that match the max/min (either by looping twice or storing them in arrays), we can capture every occurrence.
内容的提问来源于stack exchange,提问作者prof zhj

