How to write a O(n^2) method that finds the largest distance between two points

前端 未结 2 1794
自闭症患者
自闭症患者 2021-01-25 19:13

I have an array int [] nums = {5, 1, 6, 10, 4, 7, 3, 9, 2}

I want to find the distance between the smallest and largest number in that array in O(n^2) time.

相关标签:
2条回答
  • 2021-01-25 19:59

    For numbers (as opposed to points on a plane) You can do that in linear time. Find maximum, find minimum, then subtract. So, no nested loops required.

    0 讨论(0)
  • 2021-01-25 20:05

    You're overwriting the max and mins.

    if (nums[i] > nums[j])
        max = nums[i];
    else if (nums[i] < nums[j])
        min = nums[i];  
    }
    

    You need to compare the current number with the max/min that is set already. Instead you're comparing the current number with another number, and then overwriting max/min if the condition is true. In this example, at one point 10 was the max, but then you later checked if(9>2), which is true, so you changed max = 10 to max = 9.

    Here it is in O(n^2) time, with the outer loop being completely useless.

    public static int quadratic(int[] nums) {
    
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
    
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
    
                if (nums[j] > max)
                    max = nums[j];
                if (nums[j] < min)
                    min = nums[j];  
                }
            }
        System.out.println(max + " " + min);
        int maxDifference = max - min;
        return maxDifference; 
    }
    
    0 讨论(0)
提交回复
热议问题