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

前端 未结 2 1796
自闭症患者
自闭症患者 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 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; 
    }
    

提交回复
热议问题