生成二进制文件(使用DataOutputStream,使用缓冲区,耗时79秒):
File file = new File("E:test.dat"); if (!file.exists()) { file.createNewFile(); } long time = System.currentTimeMillis(); DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Random random = new Random(); long count = 200000000; System.out.println(count+"is max long int in java"); int temp; for (long i = 0; i < count; i++) { temp = random.nextInt(); stream.writeInt(temp); stream.writeChar(','); } System.out.println("循环完成"); stream.flush(); stream.close(); time = System.currentTimeMillis() - time; System.out.println(time+"毫秒");
分析文件(使用DataInputStream,使用缓冲区,耗时65秒)
a.读取前100个整数
b.排序,把排序后的数组看成堆,最小值在根节点
c.遍历整个文件,把读到的数和最小值比较,如果比最新值小,则丢弃,如果比最小值大则替换最小值重建堆。
d.文件读取完毕,堆中的元素就是要找的100个最大值,再执行一次排序。
TestRead.Javapublic static void main(String[] args) throws IOException, InterruptedException { File file = new File("E:test.dat"); long time = System.currentTimeMillis(); DataInputStream stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); int len = 100; long count = 100; int arr[] = new int[100]; for (int i = 0; i < len; i++) { arr[i] = stream.readInt(); stream.readChar(); } Arrays.sort(arr); print(arr); int temp = 0; while(true) { try { temp = stream.readInt(); stream.readChar(); count++; if(temp > arr[0]) { addToheap(arr,temp); } else { continue; } } catch(EOFException ioe) { break; } } stream.close(); time = System.currentTimeMillis() - time; System.out.println(time+"毫秒"+":"+count+"个"); Arrays.sort(arr); print(arr); } static void addToheap(int arr[], int temp){ arr[0] = temp; int index = 0; int left = 1; int right = 2; int minIndex = index; while (left < arr.length) { if (arr[index] > arr[left]) { minIndex = left; } if (right < arr.length && arr[minIndex] > arr[right]) { minIndex = right; } if (minIndex == index) { break; } else { temp = arr[minIndex]; arr[minIndex] = arr[index]; arr[index] = temp; index = minIndex; left = 2*index + 1; right = 2*index + 2; } } }static void print(int[] aa) { for (int i = 0; i < aa.length; i++) { System.out.print(aa[i] + ","); if ((i + 1) % 10 == 0) { System.out.println(); } } }
以上就是天津卓众教育java培训机构的小编针对“2020年Java易宝支付笔试题”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。
Java笔试题