输入:
如10 3 1 1 1 7 1 2 5 8 5 98877121
表示一共10条记录,求违章次数最多的3个车牌号违章次数的平均。发生违章的车辆依次是1,1,1,7,1,2,5,8,5,98877121
输出:
5
2
第一步的结果为
1,4;
2,1;
5,2;
7,1;
8,1;
98877121,1;
输出第三个id 5
1号车违章4次,5号车违章2次,2号1次,(7,8,98877121都是一次,并列的只取一个即可)5号2次 平均 (4+1+2)/3 = 2,取整即可
输出平均值2
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
//示例代码,应该会比较慢吧,本题采用文件io接口,可以直接new File("in"),new File("out")这样调用
public class Main {
public static void main(String[] args) throws Exception{
RandomAccessFile fs = new RandomAccessFile("in", "r");
FileChannel fc = fs.getChannel();
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
IntBuffer intBuffer = buffer.asIntBuffer();
PrintStream stream = new PrintStream("out");
int size = intBuffer.get();
int n = intBuffer.get();
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0 ; i< size ; i++){
int id = intBuffer.get();
if (!map.containsKey(id)){
map.put(id, 1);
} else {
map.put(id, map.get(id) + 1);
}
}
int index = map.size() / 2;
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()){
list.add(entry.getValue());
if (--index == 0){
stream.println(entry.getKey());
}
}
Collections.sort(list);
int sum = 0;
for (int i = list.size() - 1;i> list.size() -n; i--){
sum += list.get(i);
}
stream.println(sum/n);
fc.close();
stream.close();
}
}