给定一个整数数组,为每个元素找到最接近的较小或相同的元素。如果一个元素的所有元素都大,则打印-1。我们可以假设该数组至少包含两个元素。
例子:
Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 10 -1 10 10 12 11
Note that there are multiple occurrences of 10, so floor of 10 is 10 itself.
Input : arr[] = {6, 11, 7, 8, 20, 12}
Output : -1 8 6 7 12 11
一个简单的解决方案是运行两个嵌套循环。我们一个接一个地选择一个外部元素。对于每个拾取的元素,我们遍历剩余的数组并找到最接近的较大元素。该解决方案的时间复杂度为O(n * n)
更好的解决方案是对数组进行排序并创建排序后的副本,然后对地板进行二进制搜索。我们遍历数组,对于每个元素,我们搜索一个大于或等于给定元素的元素的首次出现。找到这样的元素后,我们检查它的下一个是否也相同,如果是,则存在该元素的多次出现,因此我们将相同的元素打印为输出。否则,我们将在已排序的数组中打印前一个元素。在C++中,lower_bound()将迭代器返回到排序数组中的第一个大于或等于第一个元素。
C++
// C++ implementation of efficient algorithm to find
// floor of every element
#include
using namespace std;
// Prints greater elements on left side of every element
void printPrevGreater(int arr[], int n)
{
// Create a sorted copy of arr[]
vector v(arr, arr + n);
sort(v.begin(), v.end());
// Traverse through arr[] and do binary search for
// every element.
for (int i = 0; i < n; i++) {
// Floor of first element is -1 if there is only
// one occurrence of it.
if (arr[i] == v[0]) {
(arr[i] == v[1]) ? cout << arr[i] : cout << -1;
cout << " ";
continue;
}
// Find the first element that is greater than or
// or equal to given element
auto it = lower_bound(v.begin(), v.end(), arr[i]);
// If next element is also same, then there
// are multiple occurrences, so print it
if (it != v.end() && *(it + 1) == arr[i])
cout << arr[i] << " ";
// Otherwise print previous element
else
cout << *(it - 1) << " ";
}
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = { 6, 11, 7, 8, 20, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
printPrevGreater(arr, n);
return 0;
}
Python3
# Python3 implementation of efficient
# algorithm to find floor of every element
# Prints greater elements on left
# side of every element
def printPrevGreater(arr, n) :
# Create a sorted copy of arr
v = arr.copy()
v.sort()
# Traverse through arr[] and do
# binary search for every element.
for i in range(n) :
# Floor of first element is -1 if
# there is only one occurrence of it.
if (arr[i] == v[0]) :
if (arr[i] == v[1]) :
print(arr[i], end = " ")
else :
print(-1, end = " ")
continue
# Find the first element that is greater
# than or or equal to given element
if v.count(arr[i]) > 0:
it = v[v.index(arr[i])]
else :
it = v[n - 1]
# If next element is also same, then there
# are multiple occurrences, so print it
if (it != v[n - 1] and
v[v.index(it) + 1] == arr[i]) :
print(arr[i], end = " ")
# Otherwise print previous element
else :
print(v[v.index(it) - 1], end = " ")
# Driver Code
if __name__ == "__main__" :
arr = [ 6, 11, 7, 8, 20, 12 ]
n = len(arr)
printPrevGreater(arr, n)
# This code is contributed by Ryuga
输出:
-1 8 6 7 12 11
时间复杂度:O(n Log n)
辅助空间:O(n)