我有一个包含几个重复元素的数组,我想找到最接近数组末尾的重复元素的索引

I have an array of few repetitive elements, I want to find the index of the repetitive element which is closest to end of the array

本文关键字:元素 数组 最接近 索引 包含几 有一个      更新时间:2023-10-16

我有一个包含几个重复元素的数组,我想找到最接近数组末尾的重复元素的索引。

#include<iostream>
uisng namespace std;
int main()
{
  int arr[15]={1,2,3,4,5,6,7,8,8,8,9,10,11,12,13};   // 8 is repeating 3 times
// lets find the index of element 8 which is closest from the end
 int index;
for(int i=0;i<15;i++)
  {
    if(arr[i]==8)
     {
       index=i;break;
     }
  }      
      cout<<index;
return 0;
}

这很容易,但如果数组非常大,假设数组的大小是 10^6,那么它可能需要一些时间。有人告诉我,一种经济方法是使用二叉搜索!考虑到给定的重复元素,如果有多个元素来查找最接近末尾的重复元素的索引,我如何使用二叉搜索?

显然,二分搜索是要走的路。我建议看看std::upper_bound。参考资料中还提到了实现的示例:

template<class ForwardIt, class T>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first,last);
    while (count > 0) {
        it = first; 
        step = count / 2; 
        std::advance(it, step);
        if (!(value < *it)) {
            first = ++it;
            count -= step + 1;
        } else count = step;
    }
    return first;
}

来源也 cppreference.com。