Java 找到大于其左侧元素的数组元素
数组是一种线性数据结构,其中元素存储在连续的内存位置中。
根据问题陈述,我们给定了一个包含一些随机整数值的数组,并且我们必须使用Java编程语言找出大于其所有左侧元素的数字。
让我们开始吧!
为您展示一些示例
实例-1
给定的数组= [1, 2, -3, -4, 0, 5]。
大于其所有左侧元素的数字= 2, 5
实例-2
给定的数组= [-1, 0, 4, 6, 8, -5]。
大于其所有左侧元素的数字= 0, 4, 6, 8
实例-3
给定的数组= [-2, 3, -9, 12, 0, -7]。
大于其所有左侧元素的数字= 3, 12
步骤
步骤1 − 使用静态输入方法声明一组具有一些随机整数值的数组。
步骤2 − 使用for循环来迭代所有元素,在其中我们检查当前数字是否大于其所有左侧元素。
步骤3 − 如果我们发现当前数字是从左侧元素到它的较大值,则打印出该数字并进行下一次检查。
步骤4 − 如果我们在数组中没有找到任何更大的值,则打印为“N/A”。
语法
要获取数组的长度(数组中的元素数),数组具有一个内置属性,即 length.
以下为其语法-
array.length
其中,’array’指的是数组引用。
多种方法
我们以不同的方法提供了解决方案。
- 不使用用户定义的方法
-
使用用户定义的方法
让我们逐个查看程序及其输出。
方法1:不使用用户定义的方法
在这种方法中,我们声明一个带有一些随机整数值的数组,并使用我们的算法找到当前数字是否大于其左边的所有元素,并将该数字作为输出打印。
示例
public class Main {
public static void main (String[ ] args){
//declare the first integer type array and store some random integer values
int inputArray[] = { 1,2,3,8,5};
//if no greater element present in Array
int count = 0;
//output line
System.out.println("Array elements which are greater than its all left element:");
//initiate the loop to find the greater elements
for (int i = inputArray.length - 1; i > 0; i--){
int flag = 0;
for (int j = i - 1; j >= 0; j--){
if (inputArray[i] <= inputArray[j]){
flag = 1;
break;
}
}
if (flag == 0)
System.out.print(inputArray[i] + " ");
count+=1;
}
//if no greater value detected
if(count==0){
//print not available as output
System.out.print(" N/A ");
}
System.out.print("\n");
}
}
输出
Array elements which are greater than its all left element:
8 3 2
方法2:使用用户定义的方法
在这种方法中,我们声明一个带有一些随机整数值的数组,并将该数组和数组的长度作为参数传递给用户定义的方法,在用户定义的方法中使用算法,找到当前数字大于其所有左侧元素,并将该数字打印为输出。
示例
public class Main {
public static void main (String[ ] args){
//declare the array and initialize it with integer values
int inputArray1[] = { 132, 145, 12,-121, 765};
//call the user-defined method and pass the array with its length
greaterThanLeft(inputArray1,inputArray1.length);
}
//user defined method
public static void greaterThanLeft (int[] arr,int n){
//declare an integer value for counting the greater elements
int count = 0;
//output line
System.out.println("Array elements which are greater than its all left element:");
//take a for loop to iterate and find the greater elements
for (int i = n - 1; i > 0; i--){
int flag = 0;
for (int j = i - 1; j >= 0; j--){
if (arr[i] <= arr[j]){
flag = 1;
break;
}
}
if (flag == 0)
System.out.print(arr[i] + " ");
count+=1;
}
//if no greater value detected
if(count==0){
//print not available as output
System.out.print(" N/A ");
}
System.out.print("\n");
}
}
输出
Array elements which are greater than its all left element:
765 145
在本文中,我们探讨了在Java中找到所有左侧元素均大于数组元素的不同方法。