卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16630本站已运行3320

在C++中,查找未排序数组中元素的起始索引和结束索引

在C++中,查找未排序数组中元素的起始索引和结束索引</p><p>在这个问题中,我们得到一个包含 n 个未排序整数值的数组 aar[] 和一个整数 val。我们的任务是在未排序的数组中查找元素的开始和结束索引。</p><p>对于数组中元素的出现,我们将返回,

“起始索引和结束索引”(如果在数组中找到两次或多次)。</p><p>“单个索引”(如果找到) </p><p>如果数组中不存在,则“元素不存在”。</p><p>让我们举个例子来理解问题,

示例 1

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 2
Output : starting index = 0, ending index = 5

解释</p><p>元素 2 出现两次,</p><p>第一次出现在索引 = 0 处,</p><p>第二次出现在索引处= 5

示例 2

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 5
Output : Present only once at index 2

解释</p><p>元素 5 在索引 = 2 处仅出现一次,

示例 3

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 7
Output : Not present in the array!

解决方法

解决该问题的一个简单方法是遍历数组。</p><p>我们将遍历数组并保留两个索引值:first 和last。第一个索引将从头开始遍历数组,最后一个索引将从数组尾开始遍历。当第一个和最后一个索引处的元素值相同时结束循环。

算法

  • 步骤1 - 循环遍历数组

    • 步骤1.1 - 使用第一个索引从开始遍历,使用最后一个索引进行遍历从末尾开始。

    • 步骤 1.2 - 如果任何索引处的值等于 val。不要增加索引值。

    • 步骤 1.3 - 如果两个索引的值相同,则返回。

    • < /ul>

    示例

    说明我们解决方案工作原理的程序

    #include <iostream>
    using namespace std;
    
    void findStartAndEndIndex(int arr[], int n, int val) {
       int start = 0;
       int end = n -1 ;
       while(1){
       if(arr[start] != val)
          start++;
       if(arr[end] != val)
          end--;
       if(arr[start] == arr[end] && arr[start] == val)
          break;
       if(start == end)
          break;
    }
       if (start == end ){
          if(arr[start] == val)
             cout<<"Element is present only once at index : "<<start;
          else
             cout<<"Element Not Present in the array";
       } else {
          cout<<"Element present twice at \n";
          cout<<"Start index: "<<start<<endl;
          cout<<"Last index: "<<end;
       }
    }
    int main() {
       int arr[] = { 2, 1, 5, 4, 6, 2, 9, 0, 2, 3, 5 };
       int n = sizeof(arr) / sizeof(arr[0]);
       int val = 2;
       findStartAndEndIndex(arr, n, val);
       return 0;
    }

    输出

    Element present twice at
    Start index: 0
    Last index: 8

卓越飞翔博客
上一篇: 名称混淆和extern "C"在C++中
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏