在n个范围内发生的最大整数 | Set-3
- 最后更新 : 2021年8月10日
给定N个 L到R形式的范围,任务是找出所有范围内发生的最大整数。如果存在多个这样的整数,请打印最小的那个。
例子。
**输入:**points[] = { {1, 6}, {2, 3}, {2, 5}, {3, 8}.}
**输出。**3
解释:
1发生在1个范围{1, 6}
2发生在3个范围{1, 6}, {2, 3}, {2, 5}
3发生在4个范围{1, 6}, {2, 3}, {2, 5}, {3, 8}
4发生在3个范围{1, 6},{2, 5}, {3,8}
5在3个范围{1, 6}, {2, 5}, {3, 8}
6在2个范围{1, 6}, {3, 8}
7在1个范围{3, 8}
8在1个范围{3, 8}
因此,发生最多的整数是3。**输入:**points[] = { {1, 4}, {1, 9}, {1, 2}};
**输出。**1
**办法。**这是在n个范围内出现最大整数的即兴方法。其主要思想是利用 Hashing进行坐标压缩。所以不需要创建一个频率数组,因为大范围的频率数组会超出内存的限制。下面是解决这个问题的分步算法。
- 初始化一个有序的地图名称点,以跟踪给定范围的起点和终点。
- 对于给定范围的每个起始索引,将_point[L]的值增加_1。
- 对于给定范围的每一个结束索引,将_point[R+1]的值减少_1。
- 以点的价值递增的顺序来迭代地图。注意,频率[当前点]=频率[先前点]+点[当前点]。将当前点的频率值保持在变量cur_freq中。
- 具有cur_freq最大值的点将是答案。
- 存储索引并返回。
下面是上述方法的实现。
C++
// C++ program of the above approach#include <bits/stdc++.h>using namespace std;// Function to print the most// occured element in given rangesvoid maxOccurring(int range[][2],int n){// STL map for storing start// and end pointsmap<int,int> points;for (int i = 0; i < n; i++) {int l = range[i][0];int r = range[i][1];// Increment at starting pointpoints[l]++;// Decrement at ending pointpoints[r + 1]--;}// Stores current frequncyint cur_freq = 0;// Store element with maximum frequncyint ans = 0;// Frequency of the current ansint freq_ans = 0;for (auto x : points) {// x.first denotes the current// point and x.second denotes// points[x.first]cur_freq += x.second;// If frequency of x.first is// greater that freq_ansif (cur_freq > freq_ans) {freq_ans = cur_freq;ans = x.first;}}// Print Answercout << ans;}// Driver codeint main(){int range[][2]= { { 1, 6 }, { 2, 3 }, { 2, 5 }, { 3, 8 } };int n =sizeof(range) /sizeof(range[0]);// Function callmaxOccurring(range, n);return 0;} |
输出
3
时间复杂度。O(n Logn)
空间复杂度。O(n)
读者请注意!现在不要停止学习。以学生可接受的价格掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 箭头_下降_上升
保存