
在这个问题中,我们得到一个包含 n 个未排序整数值的数组 aar[] 和一个整数 val。我们的任务是在未排序的数组中查找元素的开始和结束索引。
对于数组中元素的出现,我们将返回,
“起始索引和结束索引”(如果在数组中找到两次或多次)。
“单个索引”(如果找到)
立即学习“C++免费学习笔记(深入)”;
如果数组中不存在,则“元素不存在”。
让我们举个例子来理解问题,
示例 1
Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 2Output : starting index = 0, ending index = 5
解释
元素 2 出现两次,
第一次出现在索引 = 0 处,
第二次出现在索引处= 5
示例 2
Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 5Output : Present only once at index 2
解释
元素 5 在索引 = 2 处仅出现一次,
示例 3
Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 7Output : Not present in the array!
解决方法
解决该问题的一个简单方法是遍历数组。
我们将遍历数组并保留两个索引值:first 和last。第一个索引将从头开始遍历数组,最后一个索引将从数组尾开始遍历。当第一个和最后一个索引处的元素值相同时结束循环。
算法
步骤1 – 循环遍历数组
步骤1.1 – 使用第一个索引从开始遍历,使用最后一个索引进行遍历从末尾开始。
步骤 1.2 – 如果任何索引处的值等于 val。不要增加索引值。
步骤 1.3 – 如果两个索引的值相同,则返回。
示例
说明我们解决方案工作原理的程序
#include 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 atStart index: 0Last index: 8
以上就是在C++中,查找未排序数组中元素的起始索引和结束索引的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1443991.html
微信扫一扫
支付宝扫一扫