寻找相同Submit: 1756 Accepted:421Time Limit: 1000MS Memory Limit: 65535K
Description
有一组数,很多很多个数,里面有一个数出现了超过一半次,请你把它找出来。
Input
先是一个N (N<=400000),然后接下来一行N个数,多组数据输入。
Output
对每个Case,输出一行,这一行只含有一个在之前数列中出现超过一半次的数。每个case之后输出一个空行。
Sample Input
11
5 5 5 5 5 5 1 2 3 4 6
Sample Output
Case 1: 5
Source
#include<iostream>
using namespace std;
int b[400001];
typedef struct
{
int *a; //栈内不可定义太大数组,用动态就可以
int top;
}stack;
void initstack(stack &s) //&s 取地址
{
s.top=-1;
}
bool empty(stack &s)
{
if(s.top==-1)
return 1;
else
return 0;
}
void pushstack(stack &s,int x)
{
s.top++;
s.a[s.top]=x;
}
void popstack(stack &s)
{
s.top--;
}
int gettop(stack &s)
{
int x;
if(s.top==-1)
return -99999;
else
{
x=s.a[s.top];
return x;
}
}
int main()
{
int i,j,sum=1;
int temp;
while(cin>>j)
{
stack s;
initstack(s);
s.a=new int[j+1];
for(i=0;i<j;i++)
cin>>b[i];
for(i=0;i<j;i++)
{
temp=gettop(s);
if(b[i]!=temp)
{
if(empty(s))
pushstack(s,b[i]);
else
{
popstack(s);
}
}
else
{
pushstack(s,b[i]);
}
}
temp=gettop(s);
cout<<"Case "<<sum<<": "<<temp<<endl;
cout<<endl;
sum++;
}
return 0;
}
类栈算法 空间节省 但是时间680MS 依然不太好 需要改进 代码如下:
#include<iostream>
using namespace std;
int a[400001];
int main()
{
int i,j,n,temp;
int top;
int sum=1;
while(scanf("%d",&n)!=EOF) //cin改成scanf后 直接从680MS降到121MS 差距极为明显~~1330也顺利AC!!
{
top=-1;
for(i=0;i<n;i++)
{
scanf("%d",&temp);
if(top==-1) //如果栈空
{
top++;
a[top]=temp;
}
else
{
if(temp==a[top]) //相同入栈 不同出栈
{
top++;
a[top]=temp;
}
else
{
top--;
}
}
}
cout<<"Case "<<sum<<": "<<a[top]<<endl;
cout<<endl;
sum++;
}
return 0;
}
总体思路 由于要找超过一般的数,那么与栈顶相同的入栈,不同的话则栈顶出栈,这样超过一半的最后一定是栈顶元素~