简体   繁体   中英

Delete the highest and lowest value of an Array

I'm trying to delete the highest and lowest numbers of the array int[] ary4 = {2,17,10,9,16,3,9,16,5,1,17,14}; it works on this specific one but when I'm changing the numbers it just doesn't do what my intentions are. I know how to do it a different way but I want to solve it with this method.

public static int[] elimAll(int[] a) {
        int c = 1;
        int g = 1;
        int[] b = a.clone();
        Arrays.sort(b);

        for (int i = 0; i < b.length; i++){

            if (i == 0) {
                if (b[i] < b[c]) {
                    b[i] = 0;
                    c++;
                }else{
                    if (b[i] < b[c] && b[i] < b[i-1]) {
                        b[i] = 0;
                        c++;
                    }
                }
            }
        }

        for (int i = 0; i < b.length; i++){
            if (i == b.length-1 || i == b.length-2){
                if (b[i] >= b[b.length-1] || b[i] >= b[b.length-2]){
                    b[i] = 0;
                    g++;
                }
            }else {
                if (b[i] > b[i + 1]) {
                    b[i] = 0;
                    g++;
                }
            }
        }
        return b;
    }

Here is one way. It does not require any sorting.

int[] ary4 = {2,17,10,9,16,3,9,16,5,1,17,14};
System.out.println("Before: " + Arrays.toString(ary4));
int[] result = elimAll(ary4);
System.out.println(" After: " + Arrays.toString(result));

prints (you can see the two 17's and the lone 1 were removed)

Before: [2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14]
 After: [2, 10, 9, 16, 3, 9, 16, 5, 14]

Explanation

  • iterate thru the array finding the highest and lowest values.
  • iterate again, testing if each value is the highest or lowest.
  • if, not, add value to new array and increment index.
  • when finished, return a copy of the array, with the remaining values removed.
public static int[] elimAll(int[] array) {
  
    int highest = Integer.MIN_VALUE;
    int lowest = Integer.MAX_VALUE;
    
    for (int val : array) {
        highest = Math.max(highest, val);
        lowest = Math.min(lowest,val);
    }
   
    int k = 0;
    
    int [] result = new int[array.length];     
    for(int val : array) {
        if (val != highest && val != lowest) {
            result[k++] = val;
        }
    }
    
    return Arrays.copyOf(result, k);
}

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