检查所有值是否在链表中至少重复两次
Check if all values are repeated at least two times in linked list
我有完全相同的Elem
和List
类定义在http://www.cplusplus.com/forum/beginner/73928/
你能建议一些技巧如何写一个函数,返回true
的情况下,所有的值已经重复两次或更多次?例如
1,1,1,2,2 - true
1,2 - false
我觉得它肯定需要一个动态数组,但想不出算法
是的,制作一个std::map<int,int>
,其中计算列表中每个数字的出现次数。此计算需要遍历整个列表。
之后,对刚刚创建的std::map
进行另一次传递,并找出是否所有的值都大于或等于2。
bool twoormore()
{
int count = 0;// for counting elements in list
int temp;// temprorary element for sorting and logical part
int cik;// how much times the value has been mentioned
bool res = true;// function result
int * arr;// pointer for the upcoming dynamic array
for(start();!end();next())
{
count++;// counting the elements
}
if(count != 0){
arr = new int[count];//creating array
int i = 0;
for(start();!end();next())
{
arr[i++] = current->num;//filling array
}
/** array sorting **/
for(int i = 0;i < count;i++)
for(int j = 0; j < count; j++)
{
if(arr[j] > arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
/** sort ends **/
temp = arr[0]; // setting first element ar temp.. for upcoming check
cik = 1;// it's been its first time
for(int i = 1;i < count;i++)
{
if(arr[i] == temp)
{
cik++; continue;// if upciming element is equal to temprorary , then add 1 to counter.. and continue looping
}else
{
if(cik > 1)
{
temp = arr[i];// if everything ok, but element value changes.
cik = 1;// sets defualt
continue;
}
else
{
res = false;// other way, the value wasnt there two times
break;
}
}
}
delete arr;//deleting allocated space for array
return res;// returning bool, true or false.
}
}
函数将看起来像这样(未经测试):
std::map<int,int> m_mapCount;
std::map<int,int>::iterator m_Iterator;
for (l.start(); !l.end(); l.next()) // put the content of your linkedlist to map
{
m_mapCount[l.current->num] += 1;
}
for (m_Iterator=m_mapCount.begin(); m_Iterator!=m_mapCount.end(); m_Iterator++)
{
if(m_Iterator->second >= 2) return true;
}
相关文章:
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 为同一存储位置调用构造函数两次是否合法?
- 是否可以仅通过编写 debian/rules 来编译两次并构建单独的软件包?
- 在此示例中,向量是否复制了两次
- 阵列不能两次将相同的名称保存,当要添加新字符串时,程序应检查以查看该名称是否已经存在
- 是否值得两次通过文件进行迭代,以创建最小的数据结构
- 现代C++编译器是否能够避免在某些条件下两次调用常量函数
- 如果参数传递两次,会发生什么情况?一次按值,一次按引用?是否会修改
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量
- 检查模板参数在同类参数包中是否出现两次以上
- 是否可以两次实现[]操作员
- 如果我对async_read进行两次调用,那么只有在处理完第一次调用之后,才会处理第二次调用,这是否安全
- 两次声明纯虚拟函数(在层次结构中的两个类中)是否完全合法
- 如何检查用户是否进行了两次相同的选择
- 我是否需要锁才能同时使用同一应用程序两次写入套接字
- 对不同线程中同一位置的两次轻松写入是否总是以相同的顺序被其他线程看到
- 由于在序列点之间修改变量两次而导致的 UB 是否会转移到"inner"范围?
- 检查所有值是否在链表中至少重复两次
- 头文件是否应该插入两次
- 在使用cin时,是否有必要将一个变量存储两次