如何减少此代码的执行时间

问题描述 投票:0回答:3
import java.util.*;
import java.io.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc= new Scanner(System.in);
        int siz= sc.nextInt();
        int max= sc.nextInt();
        CircularQueue<Long> queue = new CircularQueue<>(max);
        while(siz-->0){
            queue.add(sc.nextLong());
        }
        System.out.println(queue.size());
        for(int i=queue.size();i>0;i--){     
                System.out.print(queue.get(i-1)+" ");                  
        }      

        } 
        public static class CircularQueue<E> extends LinkedList<E> {
            private int capacity = 10;

            public CircularQueue(int capacity){
                this.capacity = capacity;
            }

            @Override
            public boolean add(E e) {
                if(contains(e)){
                    return true;
                }
                if(size() >= capacity)
                    removeFirst();
                return super.add(e);
        }
    }

}

在此程序中,我创建了固定大小的链接列表,在其中添加了大于列表大小的值,然后删除了旧值,最后添加了新值。

建议在不更改逻辑的情况下对代码进行一些更改。在此先感谢

java algorithm performance execution
3个回答
1
投票

LinkedList的[contains()]在最坏的情况下具有O(n)时间。

为此目的构造辅助HashSet,或发明另一种方式来跟踪已经出现的元素。


1
投票

Scanner类对于大输入量很慢,因此请避免使用它。您可以使用比Scanner类更快的BufferedReader类。

[Scanner是比BufferedReader更强大的实用程序,但BuffredReader的缓冲区(8KB)比Scanner(1KB)大得多,而且Scanner使用正则表达式读取和解析文本输入,这使它变慢。


0
投票

在main方法中对queue.size的调用。如果您一次调用一次计算并保存其值,则可以保存一个计算,然后在sysout语句和for循环中重用。

避免广义的进口。例如导入java.io. *放入您要专门访问的软件包。这样可以节省一点时间。

© www.soinside.com 2019 - 2024. All rights reserved.