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

更新於: 2022年2月1日

165 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.