在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中查詢大於其左側所有元素的陣列元素的不同方法。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP