资源限制
时间限制: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
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ALGO79 {
static List temp = new ArrayList<Integer>();
static int CompactIntegers(int [] arr, int n) {
int returnvalue = 0;
for(int i=0; i<n; i++) {
if(arr[i] == 0) {
returnvalue++;
}else {
temp.add(arr[i]);
}
}
return returnvalue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(n - CompactIntegers(arr, n));
Object[] result = temp.toArray();
for(int i=0; i<result.length; i++) {
System.out.print((int)result[i] + " ");
}
}
}
本文介绍了一个用于删除数组中所有值为0的元素的算法,并通过示例展示了如何使用Java实现该算法,包括从键盘读取整数、处理数组以及输出处理后的数组元素。
607

被折叠的 条评论
为什么被折叠?



