Java 中将所有零移到数组末尾
在 Java 中,数组是一个对象。它是一种非原始数据类型,用于存储相同数据类型的值。
根据问题陈述,我们必须将所有零移到数组的末尾,即如果数组包含 n 个零,则所有 n 个零都将被推送到数组的末尾。
让我们探索本文,看看如何使用 Java 编程语言来实现。
展示一些示例
示例 1
假设原始数组为 {128, 0, 99, 67, 50, 0, 29, 7, 0}
将所有零移到数组末尾后的结果将是
将所有零移到数组末尾后的数组元素
128 99 67 50 29 7 0 0 0
示例 2
假设原始数组为 {23, 9, 6, 4, 0, 0, 21, 7, 0, 6, 0, 9}
将所有零移到数组末尾后的结果将是
将所有零移到数组末尾后的数组元素
23 9 6 4 21 7 6 9 0 0 0 0
示例 3
假设原始数组为 {3, 9, 5, 1, 0, 0, 11, 6, 0, 9}
将所有零移到数组末尾后的结果将是
将所有零移到数组末尾后的数组元素
3 9 5 1 11 6 9 0 0 0
算法
算法 1(使用排序)
步骤 1 - 声明并初始化一个整数数组。
步骤 2 - 实现多种方法的逻辑。
步骤 3 - 按降序对数组进行排序,因此零将位于最后一个位置。
步骤 4 - 打印数组的元素。
算法 2(通过手动迭代和替换)
步骤 1 - 声明并初始化一个整数数组。
步骤 2 - 实现多种方法的逻辑。
步骤 3 - 将所有非零元素推送到数组的左侧,零元素保留在末尾。
步骤 4 - 打印数组的元素。
语法
要获取数组的长度(该数组中的元素数量),数组有一个内置属性,即 length
下面是其语法:
array.length
其中,'array' 指的是数组引用。
多种方法
我们提供了不同方法的解决方案。
使用排序
通过手动迭代和替换
让我们逐一查看程序及其输出。
方法 1:使用排序
在这种方法中,数组元素将在程序中初始化。然后根据算法按降序对数组进行排序,因此零将位于最后一个位置。
示例
import java.util.*;
public class Main {
public static void main(String[] args){
//Declare and initialize the array elements
int array[] = {128, 0, 99, 67, 50, 0, 29, 7, 0};
//getting length of an array
int n = array.length;
//calling user defined function
func(array, n);
}
//user defined method
public static void func(int array[], int n) {
//sorting the array elements
Arrays.sort(array);
System.out.println("Elements of array after moving all the zeros to the end of array: ");
//prints array using the for loop
for (int i = n-1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
}
}
输出
Elements of array after moving all the zeros to the end of array: 128 99 67 50 29 7 0 0 0
方法 2:通过手动迭代和替换
在这种方法中,数组元素将在程序中初始化。然后根据算法将所有非零元素推送到数组的左侧,零元素保留在末尾。
示例
import java.io.*;
public class Main {
public static void main (String[] args){
//Declare and initialize the array elements
int arr[] = {3, 9, 5, 1, 0, 0, 11, 6, 0, 9};
//getting length of an array
int n = arr.length;
//calling user defined method
func(arr, n);
}
//user defined method
static void func(int arr[], int n) {
// Count of non-zero elements
int count = 0;
//shifting non zero element to the left of the loop
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
//adding the zeros to the end
while (count < n)
arr[count++] = 0;
//printing the result
System.out.println("Elements of array after moving all the zeros to the end of array: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
输出
Elements of array after moving all the zeros to the end of array: 3 9 5 1 11 6 9 0 0 0
在本文中,我们探讨了如何使用 Java 编程语言将所有零移到数组的末尾。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP