简体   繁体   English

删除数组的最高值和最低值

[英]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};我正在尝试删除数组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)印刷品(您可以看到两个 17 和一个单独的 1 被删除)

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.遍历数组查找highest值和lowest值。
  • 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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