Interview question: Find such a number in an integer array, which is greater than or equal to the number on the left and less than or equal to the number on the right

For example: {3, 1, 2, 4, 7, 10, 9, 8}such a number is 4, 7;
{1, 6, 9, 2, 1, 5, 15, 20}the number that meets the condition is 1, 15, 20.

Look at the code:

public class FindingValue {
    
    
    public static void main(String[] args) {
    
    
        /**
         * 思路:1. 这样的数只要小于或等于其右侧的最小数就满足右侧条件
         *      2. 大于或等于左侧最大的数就满足左侧条件
         */
        int[] arr = {
    
    3, 1, 2, 4, 7, 10, 9, 8};
        int[] arr1 = {
    
    1, 6, 9, 2, 1, 5, 15, 20};
        findValue(arr);
        System.out.println();
        findValue(arr1);


    }

    public static void findValue(int[] arr) {
    
    
        // 使用一个临时数组来保存 arr 中的每一个数右侧的最小值
        int[] temp = new int[arr.length];
        int min = arr[arr.length - 1];
        for (int j = arr.length - 1; j >= 0; j--) {
    
    
            if (arr[j] < min) {
    
    
                min = arr[j];
            }
            temp[j] = min;
        }
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i] > max) {
    
    
                max = arr[i];
            }
            if (arr[i] >= max && arr[i] <= temp[i]) {
    
    
                System.out.print(arr[i] + " ");
            }
        }
    }
}

Reference: Find such a number in an int array, which is greater than or equal to all numbers on the left, and less than or equal to all numbers on the right

Guess you like

Origin blog.csdn.net/jiaobuchong/article/details/86634845