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

WBOY
WBOY 转载
2023-08-29 10:17:06 572浏览

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

在这个问题中,我们得到一个包含 n 个未排序整数值的数组 aar[] 和一个整数 val。我们的任务是在未排序的数组中查找元素的开始和结束索引

对于数组中元素的出现,我们将返回,

“起始索引和结束索引”(如果在数组中找到两次或多次)。

“单个索引”(如果找到)

如果数组中不存在,则“元素不存在”

让我们举个例子来理解问题,

示例 1

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

解释

元素 2 出现两次,

第一次出现在索引 = 0 处,

第二次出现在索引处= 5

示例 2

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

解释

元素 5 在索引 = 2 处仅出现一次,

示例 3

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

解决方法

解决该问题的一个简单方法是遍历数组。

我们将遍历数组并保留两个索引值:first 和last。第一个索引将从头开始遍历数组,最后一个索引将从数组尾开始遍历。当第一个和最后一个索引处的元素值相同时结束循环。

算法

  • 步骤1 - 循环遍历数组

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

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

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

示例

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

#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

以上就是在C++中,查找未排序数组中元素的起始索引和结束索引的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除