蓝桥杯之算法训练 删除数组零元素

题目:算法训练 删除数组零元素

从键盘读入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.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int n = 0;
//      输入输入数据的个数
        n = in.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++)
        {
//          输入数据
            arr[i] = in.nextInt();
        }
//      调用函数
        compactIntegers(arr, n);
    }

    private static int compactIntegers(int[] arr, int n)
    {
        int count = 0;//非零元素的个数,也是新数组的模拟指针
        int[] tempArr = new int[n];
        for (int i = 0; i < n; i++)
        { // 用tempArr数组记录arr里的非零元素,并用count记录非零元素的数目
            if (arr[i] != 0)
            {
                tempArr[count++] = arr[i];
            }
        }
        System.out.println(count); // 输出非零元素的个数
        for (int i = 0; i < count; i++)
        { // 输出新数组
            System.out.print(tempArr[i] + " ");
        }
        return count;
    }

} 

猜你喜欢

转载自blog.csdn.net/qq_37905259/article/details/80603337
今日推荐