在 Java 中查詢陣列中小於給定數字的元素個數
陣列是一種線性資料結構,其中元素儲存在連續的記憶體位置。
根據問題陳述,查詢小於給定數字的元素個數意味著我們需要比較並僅計算陣列中較小的元素。
讓我們探索本文,看看如何使用 Java 程式語言來實現它。
為您展示一些例項
例項 1
假設我們有以下陣列
[10, 2, 3, -5, 99, 12, 0, -1] and the number is 9 Now the number of elements that are smaller than 9 are [2, 3, -5,0, -1] = 5 elements
例項 2
假設我們有以下陣列
[55, 10, 29, 74, 12, 45, 6, 5, 269] and the number is 50 Now the number of elements that are smaller than 50 are [10, 29, 12, 45, 6, 5] = 6
例項 3
假設我們有以下陣列
[556, 10, 259, 874, 123, 453, -96, -54, -2369] and the number is 0 Now the number of elements that are smaller than 0 are [-96, -54, -2369] = 3
演算法
演算法 1
步驟 1 - 儲存陣列元素
步驟 2 - 使用 for 迴圈遍歷所有陣列元素。
步驟 3 - 將所有元素與數字進行比較
步驟 4 - 使用計數器計算所有小於該數字的元素,並列印計數。
演算法 2
步驟 1 - 儲存陣列元素
步驟 2 - 對陣列進行排序。
步驟 3 - 比較並查詢大於給定數字的元素的索引
步驟 4 - 為了找到小於給定數字的元素個數,我們列印獲得的索引。
語法
要獲取陣列的長度(陣列中的元素個數),陣列有一個內建屬性,即length。
下面是它的語法:
array.length
其中,“array”指的是陣列引用。
您可以使用 Arrays.sort() 方法將陣列按升序排序。
Arrays.sort(array_name);
多種方法
我們提供了不同方法的解決方案。
不使用排序
使用排序
讓我們逐一檢視程式及其輸出。
方法 1:不使用排序
在這種方法中,我們使用 for 迴圈將所有元素與數字進行比較,並且只計算較小的元素。
示例
public class Main { public static void main(String[] args) { // The array elements int arr[] = { 556, 10, 259, 874, 123, 453, -96, -54, -2369}, num = 0; System.out.println("The array elements are-"); // Print the array elements for (int i : arr) { System.out.print(i + ", "); } // The counter two count all elements smaller than the number int count = 0; // Count all elements smaller than num for (int i = 0; i < arr.length; i++) { if (arr[i] < num) { count++; } } System.out.println("\nThe number of array elements that are smaller than " + num + " are " + count); } }
輸出
The array elements are- 556, 10, 259, 874, 123, 453, -96, -54, -2369, The number of array elements that are smaller than 0 are 3
方法 2:使用排序
在這種方法中,我們使用 Arrays.sort() 方法對陣列進行排序,然後查詢第一次出現大於該數字的元素的索引。該索引是小於該數字的元素的個數。
示例
import java.util.Arrays; public class Main{ public static void main(String[] args) { // The array elements int arr[] = { 556, 10, 259, 874, 123, 453, -96, -54, -2369}, num = 20; 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); // Find the index of the first element in the array greater than the given number int index = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > num) { index = i; break; } } // To find the number of elements smaller than // the number we print the index we onbtained System.out.println("\nThe number of array elements that are lesser than " + num + " are " + (index)); } }
輸出
The array elements are- 556, 10, 259, 874, 123, 453, -96, -54, -2369, The number of array elements that are lesser than 20 are 4
在本文中,我們探討了如何使用 Java 程式語言在陣列中查詢小於給定數字的元素個數。
廣告