简体   繁体   中英

How can i reduce Execution Time for this code

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);
        }
    }

}

In this Program I have created fixed size Linked List in which while adding values greater than the size of list then it removes old value and adds new value at Last.

Suggest some changes in code without changing the logic. Thanks in Advance

contains() of LinkedList has O(n) time at the worst case.

Construct an auxiliary HashSet for this purpose, or invent another way to trace elements which had appeared already.

Scanner class is slow for large inputs, so try to avoid it. you can use BufferedReader class which is faster than Scanner class.

Scanner is a much more powerful utility than BufferedReader but BuffredReader has a significantly large buffer (8KB) than Scanner (1KB) and also Scanner uses regular expression to read and parse text input which makes it slow.

The call to queue.size in main method. You can save one calculation if you call it once and save its value then reuse in sysout statement and in for loop.

Avoid generalizing imports. Ex. import java.io.* Put exactly the packages you want specifically to access. That may save also little bit of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM