简体   繁体   中英

How to find the minimum value in an array in a given range?

We are give 2 arrays, one array is called the original array and other is the corresponding array.

Example :

a: [5,6,5,7,5,5,5,8,9]

a': [1,2,3,1,2,3,1,2,1]

We are given 3 values: l , r and x

Let l = 3 and r = 7 , also x = 5 ,

So we check the occurrences of 5 in the range [3,7] , so a[3] , a[5] , a[6] , a[7] are the indices which contain 5 .

Now, we check the corresponding array's values, a'[3] , a'[5] , a'[6] , a'[7] which are: 3 , 2 , 3 and 1 . The minimum of these is 1 and hence the output will be : 1 .

I know the brute-force approach for multiple queries like this, but I'm interested in an efficient approach !

Optimized way to find the minimum value, checking the value of x in the range l & r , it the value is present then comparing it with the previous minimum value of x found in aDash array.

public static void minimumValue(int[] a, int aDash[], int l, int r, int x) {
    int min = Integer.MAX_VALUE;
    boolean isValueFound = false;
    for(int i = l-1; i<a.length && i<r; i++) {
        if(a[i] == x && aDash[i] < min) {
            min = aDash[i];
            isValueFound = true;
        }
    }
    if(isValueFound)
        System.out.println(min);
    else {
        //do something when no value of x is present in the array 'a'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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