简体   繁体   English

使用 Comparable 接口对零、负数和正数数组进行排序

[英]Sorting an array of zeros, negative and positive numbers with Comparable interface

class pair implements Comparable<pair>{
int x, y;
pair(int x, int y){
    this.x = x;
    this.y = y;
}
public int compareTo(pair c){
    return this.y-c.y;
}}

class Solution {
public int findMinArrowShots(int[][] points) {
    ArrayList<pair> point = new ArrayList<>(); 
    for(int i=0; i<points.length; i++){
        point.add(new pair(points[i][0], points[i][1]));
    }
    
    Collections.sort(point);
    
    int minarr=1;
    int prev =0;
    for(int i=1; i<point.size(); i++){
        if(point.get(i).x>point.get(prev).y){
            minarr++;
            prev = i;
        }
    }
    return minarr;
}}

I want to sort the array on the basis of y coordinate: but with mix of positive and negative y values it is giving me wrong(unsorted) order我想根据 y 坐标对数组进行排序:但是混合了正负 y 值,这给了我错误(未排序)的顺序

for eg: for the I/P : [[-2147483646,-2147483645], [2147483646,2147483647]] I need [-2147483646,-2147483645] first then [2147483646,2147483647] but it is ordering [2147483646,2147483647] as first then [-2147483646,-2147483645].例如:对于 I/P:[[-2147483646,-2147483645], [2147483646,2147483647]] 我首先需要 [-2147483646,-2147483645] 然后是 [2147483646,2147483647] 但它是在订购 [2147483647] 46,21446先是 [-2147483646,-2147483645]。

The problem is that you're running into integer limits.问题是您遇到了整数限制。 Java integers can't hold more than 2,147,483,647 or less than -2,147,483,648 (see max value of integer ), so when you add/subtract them you can end up with integer overflow/underflow, which is what's happening here. Java 整数不能超过 2,147,483,647 或小于 -2,147,483,648(请参阅整数的最大值),因此当您添加/减去它们时,您最终可能会出现整数溢出/下溢,这就是这里发生的情况。

The solution to integer limit issues in general is to use long , which can hold values of up to 9,223,372,036,854,775,808 and as low as -9,223,372,036,854,775,807.一般来说,整数限制问题的解决方案是使用long ,它可以保存的值最高为 9,223,372,036,854,775,808,最低为 -9,223,372,036,854,775,807。 However , here that is just stepping around the real issue: that you are inventing your own comparison method from scratch, when a built-in one designed to handle all edge cases already exists.但是,这只是绕过真正的问题:当已经存在旨在处理所有边缘情况的内置比较方法时,您正在从头开始发明自己的比较方法。

What you should be doing is calling the built-in compare() on the two y values.你应该做的是在两个 y 值上调用内置的compare() Instead of代替

return this.y - c.y

do

return Integer.compare(this.y, c.y)

which will call the built-in compare() method for integers, which is built to be able to handle all integers.它将调用整数的内置compare()方法,该方法旨在能够处理所有整数。

   if(point.get(i).x>point.get(prev).y){

改成:

   if(point.get(i).y>point.get(prev).y){

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

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