首页 > 试题广场 >

删除vector中的重复元素

[编程题]删除vector中的重复元素
  • 热度指数:86 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定vector<int>对象,删除其中的重复元素,同时保持元素本来的顺序。

输入描述:
整数集合,整数之间通过空格分隔,将这些整数存入vector<int>后,开始操作


输出描述:
去重后的元素列表,保持元素本来的顺序
示例1

输入

14 5 14 2 8 2 2 9 8

输出

14 5 2 8 9
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {

    int b,i;
    int a[10];
    i=0;
    while (cin >>b) {
        a[i]=b;
        i++;
        if(cin.get()=='\n') break;
    }
    vector<int> v(a,a+i);
    vector<int> v0;
    vector<int>::iterator it1,it2;
    for(it1=v.begin();it1!=v.end();it1++){
        it2=find(v.begin(),it1,*it1);
        if(it2==it1){
            v0.push_back(*it1);
        }
    }
    for (vector<int>::iterator it = v0.begin(); it != v0.end(); it++) {
		cout << *it<<" ";
	}

}


编辑于 2023-04-01 15:52:37 回复(0)
# include <bits/stdc++.h>
using namespace std;

int main()
{
    int num;
    unordered_set<int> hash;
    vector<int> nums;
    while(cin >> num)
        if(hash.find(num) == hash.end())
        {
            hash.insert(num);
            nums.push_back(num);
        }
    for(int tmp : nums)
        cout << tmp << " ";
    return 0;
}

发表于 2022-03-15 22:27:50 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt())
            set.add(in.nextInt());
        for (int value : set)
            System.out.print(value+" ");
    }
}

发表于 2021-09-26 10:48:49 回复(0)