Hid*_*dde 14 java arrays optimization
我有一个数组:
[0, 5, 6, 0, 0, 2, 5]
Run Code Online (Sandbox Code Playgroud)
我想从中删除所有零,以便返回(保持相同的顺序):
[5, 6, 2, 5]
Run Code Online (Sandbox Code Playgroud)
有没有比以下更简单的方法删除所有零?
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
我无法在Arrays课程中找到任何方法,Google/SO搜索也没有给我任何好的答案.
Mik*_*kis 16
这是一种罕见的情况,在代码中显示它比用简单的英语解释更容易:
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;
Run Code Online (Sandbox Code Playgroud)
Eng*_*uad 12
这个怎么样:
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));
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
[1, 3, 6, 4, 3]
Run Code Online (Sandbox Code Playgroud)
小智 5
使用 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};
Run Code Online (Sandbox Code Playgroud)