简体   繁体   中英

Java - Comparing a long list of integers

My code is timing out as it is inefficient. Program takes in a line of n integers. Each consecutive pair of integers represents a single point (x, y) this is an example of input :

-5 -10 20 25 30 2 -1 -40

Output:

java.awt.Point[x=-5,y=-10]
java.awt.Point[x=-1,y=-40]
java.awt.Point[x=20,y=25]
java.awt.Point[x=30,y=2]
4

I have the code to sort all the points. They are sorted from smallest to biggest. Where "x" values are equal, I then check the y value. The PROBLEM is this: I need to count how many times a point is bigger than every other point (both x and y). So in the above example, the answer is 4.

  • The fourth point is bigger than the first and second point.

  • The third point is bigger than the first and second.

    Which results in 4.

If points are equal, also increase the counter.

For really really longer line of integers, my program times out (killed). I can't provide the input here as it is way too long. How else can I improve the complexity?

public void calculateDomination(){
        int counter =0;
        int sizeOfList = this.coordinateList.size();
        for(int i = 0; i < sizeOfList ; i++){
            for(int j = i+1; j < sizeOfList ; j++){
                if(((this.coordinateList.get(i).x) < (this.coordinateList.get(j).x)) && ((this.coordinateList.get(i).y) < (this.coordinateList.get(j).y)) ){
                    counter++;
                }
                else if(((this.coordinateList.get(i).x) == (this.coordinateList.get(j).x)) && ((this.coordinateList.get(i).y) == (this.coordinateList.get(j).y)) ){
                    counter++;
                }
            }
        }
        System.out.println(counter);
    }

The first idea I posted, now removed, would not actually work. The one that does work:

Use an incremental sorting/counting of encountered y values:

As you go through the list, maintain a TreeMultiset of all the y values encountered so far. At each point, check the size() of the headMultiset() of nodes before the current y value. Since only values from points with lower x values will have been added to it yet, that will give you the current point's count.

I think all involved operations of TreeMultiset are O(log(n)), so this will drop your algorithm from O(n^2) to O(n * log(n)).

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