查找数组中大于其左侧相邻元素的元素?
根据题意,我们有一个包含一些随机整数值的数组,我们需要找出大于其左侧相邻元素的数字。
注意 - 使用整型数组。
让我们深入研究这篇文章,了解如何使用Java编程语言来实现。
举几个例子
示例1
给定数组 = [1, 2, -3, -4, 0, 5]。
大于其左侧元素的数字 = 2, 0, 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 an integer type array and store some random integer values
int inputArray[] = { 14, 16, 3, 5, 2};
//declare an integer variable to store the length of the given Array
int len = inputArray.length;
int count = 0;
//output line
System.out.println("Array elements which are greater than its left element:");
//take the loop to find the greater elements
for (int i = 1; i < len; i++) {
//check whether the present number is greater than its left element or not
if (inputArray[i] > inputArray[i-1]){
//print the greater elements if available
System.out.print (inputArray[i] +" ");
//increament the count value
//if any greater value found
count+=1;
}
}
//if no greater value detected
if(count==0){
//print not available as output
System.out.print(" N/A ");
}
}
}
输出
Array elements which are greater than its left element: 16 5
方法2:使用用户自定义方法
在这种方法中,我们声明一个包含一些随机整数值的数组,并将该数组和该数组的长度作为参数传递给我们的用户自定义方法,在用户自定义方法中,使用该算法查找当前数字是否大于其左侧元素,并将该数字作为输出打印。
示例
public class Main {
public static void main (String[ ] args){
//declare two arrays
int inputArray1[] = {12, 13, 92,-11, 65};
int inputArray2[] = {5, 4, 3, 2, 1};
//call the user-defined method
greaterThanLeft(inputArray1,inputArray1.length);
greaterThanLeft(inputArray2,inputArray2.length);
}
//user defined method
public static void greaterThanLeft (int[] arr,int n){
int count = 0;
System.out.println("Array elements which are greater than its left element:");
//take a for loop to find the greater elements
for (int i = 1; i < n; i++) {
//check whether the present number is greater than its left element or not
if (arr[i] > arr[i-1]){
//print the greater elements if available
System.out.print (arr[i] +" ");
//increament the count value
//if any greater value found
count+=1;
}
}
//if no greater value detected
if(count==0){
System.out.print(" N/A ");
}
System.out.print("\n");
}
}
输出
Array elements which are greater than its left element: 13 92 65 Array elements which are greater than its left element: N/A
在这篇文章中,我们探讨了使用Java编程语言查找数组中大于其左侧元素的元素的不同方法。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP