简体   繁体   English

从数组中删除所有零

[英]Remove all zeros from array

I have an array:我有一个数组:

[0, 5, 6, 0, 0, 2, 5]

I would like to remove all zeros from it, so that this returns (keeping the same order):我想从中删除所有零,以便返回(保持相同的顺序):

[5, 6, 2, 5]

Is there any easier way to remove all zeros than the following?有没有比以下更简单的方法来删除所有零?

int[] array = {0, 5, 6, 0, 0, 2, 5};
        int len = 0;
        for (int i=0; i<array.length; i++){
            if (array[i] != 0)
                len++;
        }
        int [] newArray = new int[len];
        for (int i=0, j=0; i<array.length; i++){
            if (array[i] != 0) {
                newArray[j] = array[i];
                j++;
            }
        }

I haven't been able to find any method in the Arrays class, and Google/SO searches didn't give me any good answers.我在 Arrays 类中找不到任何方法,Google/SO 搜索也没有给我任何好的答案。

This is one of those rare cases where it is easier to show it in code than to explain in plain English:这是在代码中显示它比用简单的英语解释更容易的罕见情况之一:

int targetIndex = 0;
for( int sourceIndex = 0;  sourceIndex < array.length;  sourceIndex++ )
{
    if( array[sourceIndex] != 0 )
        array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;

How about this:这个怎么样:

Integer[] numbers = {1, 3, 6, 0, 4, 0, 3};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(numbers));
list.removeAll(Arrays.asList(Integer.valueOf(0)));
numbers = list.toArray(new Integer[list.size()]);
System.out.println(Arrays.toString(numbers));

OUTPUT:输出:

[1, 3, 6, 4, 3]

With Java 8 you can make a stream out of the array, apply .filter() and then convert it back into an array :使用 Java 8,您可以从数组中创建一个流,应用 .filter() 然后将其转换回数组:

int[] array = {0, 5, 6, 0, 0, 2, 5};

int[] filteredArray = Arrays.stream(array).filter(num -> num != 0).toArray();    

// filteredArray = {5, 6, 2, 5};

This example uses Apache Commons library , I hope this will be useful to you本示例使用Apache Commons库,希望对您有用

import org.apache.commons.lang.ArrayUtils;

public class Test {
    public static void main(String args[]) {
        int[] array = {0, 5, 6, 0, 0, 2, 5};

        // this loop is to remove all zeros
        while(ArrayUtils.contains(array, 0))
            array = ArrayUtils.removeElement(array, 0);

        // this loop will print the array elemnents
        for(int i : array)
            System.out.println(i);

    }
}

You can achieve this with one loop only.你可以只用一个循环来实现这一点。 Whether this is better or more clear is a matter of personal taste I am afraid.恐怕这更好或更清楚是个人品味的问题。

int[] array = {0, 5, 6, 0, 0, 2, 5};
int[] temp = new int[array.length];
int numberOfZeros = 0;
for (int i=0; i<array.length; i++){
  if (array[i] != 0){
    temp[i-numberOfZeros] = array[i];
  } else {
    numberOfZeros++;
  }
}
int[] result = new int[temp.length-numberOfZeros];
System.arraycopy(temp, 0, result, 0, result.length);

Another option would be to use a List implementation like ArrayList from which you can just remove elements, but then you will have to work with Integer instances and not with int s另一种选择是使用像ArrayList这样的List实现,您可以从中删除元素,但是您将不得不使用Integer实例而不是int s

List<Integer> originalList = ....;
Iterator<Integer> iterator = originalList.iterator();
while ( iterator.hasNext() ) {
  Integer next = iterator.next();
  if ( next == 0 ){
    iterator.remove();
  }
}
//convert to array if needed
Integer[] result = originalList.toArray( new Integer[originalList.size()]);

Does the programming language you use employ .map or .reduce functions, or is there an extension that allows you to do this?您使用的编程语言是否使用 .map 或 .reduce 函数,或者是否有允许您执行此操作的扩展?

In Swift, you can do this via .filter;在 Swift 中,你可以通过 .filter 来做到这一点; observe观察

var orders = [0, 5, 6, 0, 0, 2, 5]

orders = orders.filter({ $0 != 0 })

print (orders)

This returns [5, 6, 2, 5] , retaining your order这将返回[5, 6, 2, 5] ,保留您的订单

You can remove zeros in O(1) extra space.您可以删除 O(1) 额外空间中的零。 Instead of copying the elements into another array you can just return the size and print the same array:而不是将元素复制到另一个数组中,您只需返回大小并打印相同的数组:

public class RemoveZeros {
    
    static int removeZeros(int[] a){
        int j =0;
        
        for(int i =0;i<a.length;i++) {
            if(a[i] !=0) {
                a[j] = a[i];
                j++;
            }
            
        }
        
        return j;
    }
    public static void main(String[] args) {
        int[] a = new int[]{0, 5, 6, 0, 0, 2, 5};
        int val = removeZeros(a);
        for(int i =0;i<val;i++)
            System.out.println(a[i]);
    }
}

Try the basic way:尝试基本方法:

public int[] convert(int[] data) {
    int count =0;
    for (int i =0; i< data.length; i++) {
        if(data[i]==0)
            count++;
    }
    int[] nonZero = new int[data.length-count];
    int j =0;
    for(int i = 0; i<data.length; i++) {
        if(data[i]!=0) {
            nonZero[j] = data[i];
            j++;
        }
    }
    return nonZero;
}

You can use a Vector :您可以使用Vector

Vector vec = new Vector();
for (int i=0; i<array.length; i++){
   if (array[i] != 0)
      vec.add(array[i]);
}
vec.toArray()

(this isn't the precise syntax, but you get the idea..) (这不是精确的语法,但您明白了..)

如果你被允许使用 List 而不是数组,你实际上除了创建一个新的 Iteratable 接口并像google-collections Collections2.filter() 那样对其应用一个方法之外什么都不做,你可以查看它。

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

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