Java 查找至少有一个较小元素的数组元素
数组是一种线性数据结构,其中元素存储在连续的内存位置中。
根据问题陈述,我们需要打印所有至少有一个较小元素的元素。简单地说,我们可以将数组的所有元素打印出来,除了最小的元素,因为最小的元素没有任何比它更小的元素。
让我们探索一下这篇文章,看看如何使用Java编程语言来实现它。
一些示例
示例1
Suppose we have the below array
[10, 2, 3, -5, 99, 12, 0, -1]
Now all elements that have at least one smaller element are = 10, 2, 3, 99, 12, 0, -1
示例2
Suppose we have the below array
[55, 10, 29, 74, 12, 45, 6, 5, 269]
Now all elements that have at least one smaller element are = 55, 10, 29, 74, 12, 45, 6, 269
示例3
Suppose we have the below array
[556, 10, 259, 874, 123, 453, -96, -54, -2369]
Now all elements that have at least one smaller element are = 556, 10, 259, 874, 123, 453, -96, -54
步骤
步骤-1
- 第一步: - 存储数组元素。
-
第二步: - 使用for循环遍历所有数组元素。
-
第三步: - 比较所有元素以找到最小的元素。
-
第四步: - 使用foreach循环打印除最小元素以外的所有元素。
步骤-2
-
第一步: - 存储数组元素。
-
第二步: - 按升序对数组进行排序。
-
第三步: - 使用for循环从第二个元素到最后一个元素遍历并打印所有元素。
语法
要获取数组的长度(即数组中的元素个数),数组有一个内置属性, length −
以下是其语法表示 –
array.length
Where ‘array’ refers to the array reference.
你可以使用Arrays.sort() 方法将数组按升序进行排序。
Arrays.sort(array_name);
多种方法
我们以不同的方法提供了解决方案。
- 不使用排序
-
使用排序
让我们逐个查看程序及其输出。
方法1:不使用排序
在这种方法中,我们使用一个循环来找出最小的元素,然后打印除此元素之外的所有元素。
示例
public class Main {
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, 99, 12, 10 };
System.out.println("The array elements are-");
// Print the array elements
for (int i : arr) {
System.out.print(i + ", ");
}
// Initialize the first element as smallest and compare
int smallest = arr[0];
// Find the smallest element in the array
for (int i = 0; i < arr.length; i++)
if (arr[i] < smallest)
smallest = arr[i];
// Print array elements that have at least one smaller element
System.out.println("\nThe array elements that have at least one smaller element are-");
for (int i : arr) {
if (i != smallest)
System.out.print(i + ", ");
}
}
}
输出
The array elements are-
10, 2, 3, 99, 12, 10,
The array elements that have at least one smaller element are-
10, 3, 99, 12, 10,
方法2:使用排序
在这种方法中,我们使用Arrays.sort()方法对数组进行排序,然后打印除第一个元素之外的所有元素。
示例
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// The array elements
int arr[] = { 10, 2, 3, 99, 12, 10 };
System.out.println("The array elements are-");
// Print the array elements
for (int i : arr) {
System.out.print(i + ", ");
}
// Sort the array
Arrays.sort(arr);
// Print the array elements from the 2nd element
System.out.println("\nThe array elements that have at least one smallerelement are-");
for (int i = 1; i < arr.length; i++) {
System.out.print(arr[i] + ", ");
}
}
}
输出
The array elements are-
10, 2, 3, 99, 12, 10,
The array elements that have at least one smallerelement are-
3, 10, 10, 12, 99,
在本文中,我们探讨了如何使用Java编程语言找到所有至少有一个较小元素的数组元素。