【蓝桥杯】删除数组零元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/84666984
从键盘读入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.Scanner;

public class Main {
	static ArrayList<Integer> list = new ArrayList<>();
	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();
		}
		int num = CompactIntegers(a,n);
		System.out.println(num);
		for(Integer i:list){
			System.out.print(i+" ");
		}
		System.out.println();
		sc.close();
	}

	private static int CompactIntegers(int[] a, int n) {
		if(a.length<=0||n<=0){
			return 0;
		}
		int sum=0;
		for(int i=0;i<n;i++){
			if(a[i]!=0){
				list.add(a[i]);
				sum++;
			}
		}
		return sum;
		
	}
}

最直接的方式,新建一个数组将原数组中不是0的元素添加进去

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/84666984
今日推荐