You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找数组中重复元素的所有位置及对应代码修改方案

嘿,我来帮你解决这两个数组查找的问题:

问题1:如何查找数组中所有重复元素的位置?

要找出数组中所有重复元素的位置,核心思路是先记录每个元素出现的所有索引,再筛选出那些出现次数≥2的元素。用C++实现的话,可以借助std::unordered_map来高效存储元素与对应索引列表的映射:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

void findAllDuplicates(int Array[], int size) {
    unordered_map<int, vector<int>> elementPositions;

    // 遍历数组,记录每个元素的所有索引
    for (int i = 0; i < size; ++i) {
        elementPositions[Array[i]].push_back(i);
    }

    // 输出重复元素及其位置
    cout << "重复元素的位置:" << endl;
    for (auto& pair : elementPositions) {
        if (pair.second.size() > 1) {
            cout << "元素 " << pair.first << " 出现在索引:";
            for (int pos : pair.second) {
                cout << pos << " ";
            }
            cout << endl;
        }
    }
}

int main() {
    int my_array[] = {12,12,5,6,9,45,5,54,45};
    int size = sizeof(my_array) / sizeof(my_array[0]);
    findAllDuplicates(my_array, size);
    return 0;
}

运行这段代码后,会输出所有出现多次的元素及其对应的索引,比如元素12在0、1位置,元素5在2、6位置,元素45在5、8位置。


问题2:修改给定C++代码,实现查找指定重复元素的所有位置

你的原代码只能返回第一个匹配的索引,要改成返回所有匹配位置,需要做3处关键修改:

  1. 把函数返回类型从int改成vector<int>,用来存储多个索引;
  2. 遍历整个数组,找到匹配项就加入vector,不再找到第一个就返回;
  3. 在main函数中处理返回的vector,输出所有位置(空vector则提示未找到)。

修改后的完整代码如下:

#include <iostream>
#include <vector>
using namespace std;

// 返回存储所有匹配索引的vector
vector<int> findNumber(int Array[], int keyword, int size) {
    vector<int> positions;
    for (int y = 0; y < size; y++) {
        if (keyword == Array[y]) {
            positions.push_back(y); // 找到匹配就加入vector,不直接返回
        }
    }
    return positions; // 返回所有位置,空vector表示未找到
}

int main() {
    int my_array[] = {12,12,5,6,9,45,5,54,45};
    int searchInput;
    cout << "please select number to search from these (12,12,5,6,9,45,5,54,45) : ";
    cin >> searchInput;

    int size = sizeof(my_array) / sizeof(my_array[0]);
    vector<int> result = findNumber(my_array, searchInput, size);

    if (result.empty()) {
        cout << "Number " << searchInput << " not found in the array." << endl;
    } else {
        cout << "Number " << searchInput << " found at indices: ";
        for (int pos : result) {
            cout << pos << " ";
        }
        cout << endl;
    }

    return 0;
}

测试一下:输入12会输出Number 12 found at indices: 0 1 ,输入45则输出Number 45 found at indices: 5 8 ,完全满足查找指定重复元素所有位置的需求。


内容的提问来源于stack exchange,提问作者AhmedO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:16:08