简体   繁体   English

Java - 比较一长串整数

[英]Java - Comparing a long list of integers

My code is timing out as it is inefficient.我的代码由于效率低下而超时。 Program takes in a line of n integers.程序接收一行 n 个整数。 Each consecutive pair of integers represents a single point (x, y) this is an example of input :每对连续的整数代表一个点 (x, y) 这是输入的一个例子:

-5 -10 20 25 30 2 -1 -40 -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.在“x”值相等的情况下,我然后检查 y 值。 The PROBLEM is this: I need to count how many times a point is bigger than every other point (both x and y).问题是:我需要计算一个点比其他所有点(x 和 y)大多少倍。 So in the above example, the answer is 4.所以在上面的例子中,答案是 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.结果是 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:使用遇到的y值的增量排序/计数:

As you go through the list, maintain a TreeMultiset of all the y values encountered so far.当您浏览列表时,维护一个TreeMultiset遇到的所有y值的TreeMultiset At each point, check the size() of the headMultiset() of nodes before the current y value.在每个点处,检查size()的的headMultiset()当前节点之前的y值。 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.由于只有来自具有较低x值的点的值才会被添加到其中,这将为您提供当前点的计数。

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)).我认为TreeMultiset涉及的所有操作都是 O(log(n)),所以这会将您的算法从 O(n^2) 降为 O(n * log(n))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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