在 C++ 中计算排序旋转数组中小于或等于给定值的元素个数
给定一个整数数组。该数组是一个排序后的旋转数组。目标是找到数组中小于或等于给定数字 K 的元素个数。
方法是遍历整个数组,并计算小于或等于 K 的元素个数。
输入
Arr[]= { 1,2,3,4,9,8,10 } K=4输出
Elements less than or equal to 4 : 4
说明 − 小于等于 4 的元素是 1, 2, 3, 4,个数为 4
输入
Arr[]= { 5,3,6,1,8,100,12,31 } K=3输出
Elements less than or equal to 3: 2
说明 − 小于等于 3 的元素是 1, 3,个数为 2
下面程序中使用的方法如下
整数数组 Arr[] 用于存储整数,K 表示一个数字。
整数 'n' 存储数组的长度。
变量 count 用于存储小于或等于 K 的数字的个数。
从第一个元素(索引 = 0)开始遍历数组一次。
如果当前元素 <= K,则 count 自增。
Count 包含所需结果。
显示结果。
示例
#include <iostream>
using namespace std;
int main(){
int Arr[]= { 4,5,8,1,3,7,10,9,11 };
int k=7;
int n=sizeof(Arr)/sizeof(Arr[0]);
int count=0;
for(int i=0;i<n;i++)
if(Arr[i]<=k)
count++;
std::cout<<"Elements less than or equal to "<<k<<" in given sorted rotated array : "<<count;
return 0;
}输出
Elements less than or equal to 7 in given sorted rotated array : 5
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP