题目描述
从键盘读入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
解题思路
逆序遍历数组,遇到0就把0后面的所有元素移到前面,不是0就继续向前直至数组遍历完成
代码
import java.util.*;
public class DeleteZeroInArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[n];
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int newCount = compactIntegers(array, n);
System.out.println(newCount);
for (int i = 0; i < newCount; i++) {
System.out.print(array[i]);
if(i < newCount - 1)
System.out.print(" ");
}
}
public static int compactIntegers(int[] array, int n) {
int newCount = n; //记录不为0的元素个数
int i = n - 1; //i初始指向数组最后一个元素(逆序遍历数组)
while(i >= 0) {
if(array[i] == 0) { //如果元素为0则把后面的元素往前移(即0一直往后移)
newCount--;
int j = i;
while(j < n) {
if(j + 1 < n) {
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
j++;
}
else {
i--;
break;
}
}
}
else {
i--;
}
}
return newCount;
}
}