Problem Description
“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.
“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.
“But what is the characteristic of the special integer?” Ignatius asks.
“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…..” feng5166 says.
Can you find the special integer for Ignatius?
Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.
Output
For each test case, you have to output only one line which contains the special number you have found.
Sample Input
5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1
Sample Output
3
5
1
题目大意:
给定一个大小为奇数n的数组 ,要求找出其中出现次数超过n/2的那个特殊数。
解题思路:
直接排序 ,因为特殊数出现的次数大于 n/2 , 所以排序之后,处在中间位子上的那个数一定就是需要找的那个特殊数。
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
//方法一
/*因为数的总个数为奇数个,而特殊数的个数要大于总数的一半 ,
对数组进行排序 , 排在中间位置上的那个数即为 特殊数。*/
int num[500010];
int main(){
int n , i;
while(scanf("%d" , &n) != EOF){
for(i = 0 ; i < n ; i ++)
scanf("%d",&num[i]);
sort(num , num + n );
printf("%d\n" , num[n/2]);
}
return 0;
}
时间复杂度分析:
使用了sort函数进行排序 , 而sort函数所使用的排序方法是快排,所以时间复杂度为O(nlogn);
优化:
转自:https://blog.youkuaiyun.com/to_be_better/article/details/50557796 思路三。
代码 :
#include <cstdio>
#include <algorithm>
using namespace std;
/*设置一标志量num,按照原顺序依次迭代,随便假定一个解,如果a[i]==ans,num++,否则num–,
当num为0时将当前a[i]作为新解。
因为n为奇数,且特殊值出现次数大于一半,
所以任何情况下,特殊值做为解时代num不会小于1,所以最终的解一定就是特殊值。*/
int arr[500010];
int main(){
int n , i;
while(scanf("%d" , &n) != EOF){
int num = 0;
int ans = -1;
for(i = 0 ; i < n ; i ++){
scanf("%d",&arr[i]);
if(num == 0){
num ++;
ans = arr[i];
}else{
if(arr[i] == ans)
num++;
else
num--;
}
}
printf("%d\n" , ans);
}
return 0;
}
时间复杂度:
对数组一次遍历 , 所以时间复杂度为O(n)。