C++中相同数组中每个元素的向下取整
在这个问题中,我们给定一个整数元素数组 arr[]。我们的任务是创建一个程序来查找相同数组中每个元素的向下取整。如果元素的向下取整存在,我们将打印向下取整,否则打印 -1。
数组中元素的向下取整是指数组中小于或等于该元素的最接近的元素。
让我们举个例子来理解这个问题
Input: arr[] = {3, 1, 5 ,7, 8, 2}
Output: 2 -1 3 5 7 1解决方案方法
解决问题的一种方法是使用嵌套循环。一个循环用于遍历数组的每个元素,另一个循环用于在数组中查找元素的向下取整。
解决问题的另一种方法是使用一个额外的数组来存储排序后的数组。然后遍历原始数组并在排序后的数组中使用二分查找算法查找元素的向下取整。
示例
程序说明我们解决方案的工作原理
#include <bits/stdc++.h>
using namespace std;
void printFloorEle(int arr[], int n){
vector<int> sortedArr(arr, arr + n);
sort(sortedArr.begin(), sortedArr.end());
for (int i = 0; i < n; i++) {
if (arr[i] == sortedArr[0]) {
if (arr[i] == sortedArr[1])
cout<<arr[i];
else
cout<<-1;
cout<<"\t";
continue;
}
auto iterator = lower_bound(sortedArr.begin(),sortedArr.end(), arr[i]);
if (iterator != sortedArr.end() && *(iterator + 1) == arr[i])
cout<<arr[i]<<"\t";
else
cout<<*(iterator - 1)<<"\t";
}
}
int main(){
int arr[] = { 3, 1, 5 ,7, 8, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The Floor of every element of the given array is ";
printFloorEle(arr, n);
return 0;
}输出
The Floor of every element of the given array is 2 -1 3 5 7 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP