gpt4 book ai didi

C++计算给定的不同数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:28:03 26 4
gpt4 key购买 nike

程序必须计算来自标准输入的不同数字。例如,当输入

6 <- how many numbers
1
3
1
4
3
786345

它应该给出

4

这是我的解决方案,虽然它太慢了。有没有更快的方法?

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

vector<int> occured; //vector of numbers that occured already

/*
int findType(int find)
finds where given number should be, I want to keep this array sorted.
in case of number existed already return -1; otherwise return the index for inserting.
*/
int findType(int find)
{
for (int i=0; i<occured.size(); i++) //for each number in occured array
if (find==occured[i]) return -1; //if it is same return it occured
else if (find<occured[i]) return i;
return occuerd.size();
};

int main(int argc, char *argv[])
{
int n; // read how many numbers will be given
cin>>n;
int tmp; //temp variables.
int tmp2;

for (int i=0; i<n; i++) //for each number
{
cin>>tmp; //get it
if ((tmp2=findType(tmp))!=-1) //check if it occured
occured.insert(occured.begin()+tmp2,tmp); // if not add it to occured vector.
}
cout<<occured.size(); //print how many different numbers

//system("PAUSE"); //uncomment if needed
return 0;
}

最佳答案

如何使用 std::set 而不是 std::vector?它将确保没有条目存在两次(你不必检查它;它也会被排序),而且你只需要获取大小来了解不同元素的数量。

例子:

std::set<int> occured;
int tmp;
int n = 10; // or input it

for (int i=0; i<n; i++) {
cin >> tmp;
occured.insert(tmp);
}

cout << occured.size();

关于C++计算给定的不同数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9895005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com