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

如何通过遍历实现C++ vector去重且不引入algorithm库

首先在代码开头补充iostream头文件,否则cout调用会编译报错:

#include <iostream>
#include <vector>

using namespace std;
// 其余原有声明保持不变

deleteRepeats 函数的完整实现如下,完全基于遍历实现,无需引入algorithm库:

vector<int> deleteRepeats(const vector<int>& nums) {
    vector<int> res;
    bool foundRepeat;
    // 遍历原数组每一个元素
    for (int i = 0; i < nums.size(); ++i) {
        foundRepeat = false;
        // 检查当前元素是否已经存入结果数组
        for (int j = 0; j < res.size(); ++j) {
            if (nums[i] == res[j]) {
                foundRepeat = true;
                break;
            }
        }
        // 无重复则加入结果数组
        if (!foundRepeat) {
            res.push_back(nums[i]);
        }
    }
    return res;
}

该实现会保留元素第一次出现的顺序,你提供的4组测试用例均可正常通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:06:04