15:求序列中的衆數
總時間限制:
1000ms
內存限制:
65536kB
描述
輸入一個長度爲N的整數序列 (不多於128個整數),每個整數的範圍在[-1052,1052],計算這個序列的衆數。
衆數是指出現次數最多的那個數。
如果有多個數出現的次數都達到最多,則取在原序列最先出現的數爲衆數;如果所有的數都相等,則返回"no"。
輸入
第一行爲序列長度N。
然後是N個數,每一個數的範圍都是在[-10^52,10^52]。 注意,這N個數之間可能有若干個空行隔開。
注意,輸入數據可能有一些冗餘表達信息,具體來說:
1) 正數和0前面可能有前導0和'+'符號,例如
+000123=123
+0000=0
-0000=0
2)每個數字中不含有空格和其他非數字字符,例如不會出現"100 0"或者"- 100"。
3)每個數字前面至多有一個符號,即不會出現+(-1)、-(+4)和-(-1)等情況。
輸出
輸出只有 1 行:
該序列的衆數或者”no”。
如果有多個數出現的次數都達到最多,則取最先出現的數爲衆數,並且輸出形式應該最簡形式。
例如,如果原序列衆數爲+000123,則輸出123;如果原序列衆數爲+0000或者-0000或者0000,輸出0。
負數正常輸出,例如:如果原序列衆數爲-000000001111,就輸出-1111。
樣例輸入
6 -00001 10000 00011111111111111111111111111111111111 -01 +000000011111111111111111111111111111111111 -00000000000001
樣例輸出
-1
算法分析:
直接大數類+treemap
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Map;
public class Main {
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
LinkedHashMap<BigInteger,Integer> map=new LinkedHashMap<BigInteger, Integer>();
int n=cin.nextInt();
for(int i=1;i<=n;i++)
{
BigInteger b=cin.nextBigInteger();
// System.out.print(b);
if(map.get(b)==null)
{
map.put(b, 1);
}
else
{
map.put(b, map.get(b)+1);
}
}
List<Map.Entry<BigInteger,Integer>> list = new ArrayList<Map.Entry<BigInteger,Integer>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<BigInteger, Integer>>(){
//降序排序
public int compare(Entry<BigInteger,Integer> o1,Entry<BigInteger ,Integer> o2) {
return o2.getValue()-o1.getValue();
}
});
if(map.size()==1)
{
System.out.print("no");
}
else
{
for(Map.Entry<BigInteger, Integer> mapping:list) {
System.out.print(mapping.getKey());
break;
}
}
}
}