从数组中删除所有零
我有一个数组:
[0, 5, 6, 0, 0, 2, 5]
我想从中删除所有零,以便返回(保持相同的顺序):
[5, 6, 2, 5]
是否有更简单的方法来删除全部为零而不是以下?
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++; } }
我无法在Arrays课程中找到任何方法,Google / SO搜索也没有给我任何好的答案。
这是一种罕见的情况,其中更容易在代码中显示它而不是用简单的英语解释:
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;
这个怎么样:
Integer[] numbers = {1, 3, 6, 0, 4, 0, 3}; List list = new ArrayList (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]
您只需一个循环即可实现此目的。 无论是更好还是更清楚,我担心的是个人品味问题。
int[] array = {0, 5, 6, 0, 0, 2, 5}; int[] temp = new int[array.length]; int numberOfZeros = 0; for (int i=0; i
另一个选择是使用像ArrayList
这样的List
实现,你可以从中删除元素,但是你必须使用Integer
实例而不是int
List originalList = ....; Iterator 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()]);
这个例子使用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); } }
你可以使用Vector
:
Vector vec = new Vector(); for (int i=0; i
(这不是精确的语法,但你明白了......)
如果您被允许使用List而不是数组,那么除了创建一个新的Iteratable接口并像google-collections Collections2.filter()那样应用一个方法之外,你可以做任何其他事情,你可以查看它。
您使用的编程语言是否使用.map或.reduce函数,或者是否有允许您执行此操作的扩展?
在Swift中,您可以通过.filter执行此操作; 守
var orders = [0, 5, 6, 0, 0, 2, 5] orders = orders.filter({ $0 != 0 }) print (orders)
这将返回[5, 6, 2, 5]
5,6,2,5 [5, 6, 2, 5]
,保留您的订单