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.csdn.net/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)。