C++中給定範圍內最小元素的個數
給定一個大小為 N 的整數陣列。變數 L 和 R 定義了 1 到 N 之間的範圍。目標是找到在 L 和 R 範圍內(L>=1 且 R<=N)的最小元素的個數。
我們將透過遍歷 L 和 R 範圍內的元素來找到最小值。
再次遍歷 L 和 R 範圍內的元素,如果任何元素等於步驟 1 中計算出的最小值,則遞增計數器。
讓我們透過例子來理解。
輸入 − arr[]= { 1,2,3,0,3,2,0,1 }, N=8, L=2, R=5
輸出 − 範圍內最小值的個數 − 1
解釋 −
L(1) 到 R(5) 範圍內的元素是 arr[1] 到 arr[4]。{ 2,3,0,3 }。最小值為 0。0 的個數為 1。
輸入 − arr[]= { 1,2,3,0,3,2,0,1 }, N=8, L=3, R=8
輸出 − 範圍內最小值的個數 − 2
解釋 −
L(3) 到 R(8) 範圍內的元素是 arr[2] 到 arr[7]。{ 3,0,3,2,0,1 }。最小值為 0。0 的個數為 2。
下面程式中使用的方法如下
我們使用一個用隨機數初始化的整數陣列 arr[]。
整數 L 和 R 表示 arr[] 內的範圍。count 儲存 L 和 R 範圍內最小值的個數。
函式 countSmallest(int arr[],int n,int l, int r) 接收一個數組、它的長度、L 和 R 作為輸入,並返回範圍內最小值的個數。
初始化 smallest=arr[l],即最左邊的元素,並將最小值的初始計數設定為 0。
如果 l<0 且 r>=n,則返回 0,表示提供的範圍無效。
從索引 l-1 到 r-1 開始遍歷陣列。如果 arr[i]
再次遍歷從 l-1 到 r-1 的陣列,如果 arr[i]==smallest,則遞增 count。
返回 count 作為所需結果。
在 main 函式中,顯示 count 中的結果。
示例
#include <bits/stdc++.h>
using namespace std;
// Function to find if number is prime
int countSmallest(int arr[],int n,int l, int r){
int smallest=arr[l];
int count=0;
if(l<0 && r>=n)
return 0;
for(int i=l-1;i<r;i++){
if(arr[i]<=smallest){
smallest=arr[i];
}
}
for(int i=l-1;i<r;i++){
if(arr[i]==smallest){
++count;
}
}
return count;
}
int main(){
int arr[] = { 3,2,1,1,2,3 };
int n = 6;
int L,R;
int count=0;
L=1,R=5;
count=countSmallest(arr,n,L,R);
cout<<endl<<"Count of number of smallest in given range:"<<count;
L=3,R=4;
count=countSmallest(arr,n,L,R);
cout<<endl<<"Count of number of smallest in given range:"<<count;
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Count of number of smallest in given range:2 Count of number of smallest in given range:2
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP