試題 算法訓練 刪除數組零元素
資源限制
時間限制:1.0s 內存限制:512.0MB
從鍵盤讀入n個整數放入數組中,編寫函數CompactIntegers,刪除數組中所有值爲0的元素,其後元素向數組首端移動。注意,CompactIntegers函數需要接受數組及其元素個數作爲參數,函數返回值應爲刪除操作執行後數組的新元素個數。輸出刪除後數組中元素的個數並依次輸出數組元素。
樣例輸入: (輸入格式說明:5爲輸入數據的個數,3 4 0 0 2 是以空格隔開的5個整數)
5
3 4 0 0 2
樣例輸出:(輸出格式說明:3爲非零數據的個數,3 4 2 是以空格隔開的3個非零整數)
3
3 4 2
樣例輸入:
7
0 0 7 0 0 9 0
樣例輸出:
2
7 9
樣例輸入:
3
0 0 0
樣例輸出:
0
package Main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
for (int i = 0; i < n; i++) {
a[i]=sc.nextInt();
}
String s="";
int bb=0;
for (int j = 0; j < a.length; j++) {
if(a[j]!=0) {
s=s+a[j]+" ";
bb++;
}
}
System.out.println(bb);
System.out.println(s);
sc.close();
}
}