Given an array A[i..j] find out maximum j-i such that A[i]<a[j]
来源:互联网 发布:中国武术 知乎 编辑:程序博客网 时间:2024/05/13 14:17
//Given an array A[i..j] find out maximum j-i such that A[i]<a[j] in//O(n) timestruct REC{int nIndex;int nVal;};bool lessThan(const REC& rec1, const REC& rec2){return rec1.nVal < rec2.nVal;}//sort the array by value.go through the array, find//the max gap of two indexesint GetRes(int a[], int n){REC* recs = new REC[n];for (int i = 0; i < n; i++){recs[i].nIndex = i;recs[i].nVal = a[i];}sort(recs, recs+n, lessThan);int nMinIndex = recs[0].nIndex;int nRet = 0;for(int i = 1; i < n; i++){if (recs[i].nIndex > nMinIndex)nRet = max(nRet, recs[i].nIndex-nMinIndex);//如果下标大于nMinIndex,就要计算下gapelsenMinIndex = recs[i].nIndex;//如果遇到比nMinIndex小的下标,就更新最小下标。这是因为数组已经按照从小到大排序,所以只要找到最小下标,}delete []recs;return nRet;}//O(n) solutionint GetLongestDist(int a[], int n){if (a == NULL || n <= 0)return -1;vector<int> vec;for (int i = 0; i < n; i++)//存储最先遇到的最小值的下标,可以得出,求得的gap(i,j)中的i,肯定在vec中。可以通过反证法证明。{if (vec.empty() || a[i] < a[vec.back()])vec.push_back(i);}int nRet = -1;int i = vec.size()-1;int j = n-1;while (i >= 0)//通过两个指针,一个指向数组,一个指向vec{while (a[j] <= a[vec[i]] && j > vec[i])j--;if (j > vec[i])nRet = max(nRet, j-vec[i]);i--;}return nRet;}
第三种算法的时间复杂度是o(nlogn)
用一个数组b[i]记录a[0]...a[i]的最小值
所以b[]是不上升数组
对a中的每一个值a[i]用二分查找法,在b中查找小于a[i]的最大的值,计算gap
- Given an array A[i..j] find out maximum j-i such that A[i]<a[j]
- CareerCup Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.
- CareerCup Find 3 indexes i,j,k such that, i<j<k and a[i] < a[j] < a[k]
- 程序性能优化:a[i][j]与a[j][i]
- Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive
- cuda计算C[i][j]=A[i][j]+B[i][j]
- 【分治法】在数组A中,返回i<j,且A[i]>A[j]的(i,j)配对的数量
- 数组a[i++]=j 与 a[i]++ 的区别
- 关于二维数组a[i][j]
- 一个数组a[0...n-1],求a[i]-a[j]的最大值,其中i>j
- 一个数组a[0...n-1],求a[j]-a[i]的最大值,其中i<j
- 找数组的i,j(j>i)使得a[j] - a[i]的值最大(算法)
- 【谷歌面试题】给出一个数组A,找出一对 (i, j)使得A[i] <= A[j] (i < j)并且j-i最大
- a[i][j]与a[j][i]性能差别的原因
- 阅读 找数字a[i][j]!=a[j][i] 特定格式输出
- 第 15 周项目 a[i][j]<<a[j][i] 二维数组变形
- 求a[j]-a[i]的最大值,其中j>=i
- 运算优先级的坑a[i++] = a[j]
- 构建eLua
- 数组大折腾(第十四周上机任务)
- linux 编译的问题
- 数据导入导出
- 一步一步学JBPM(12)——JBPM流程历史追踪
- Given an array A[i..j] find out maximum j-i such that A[i]<a[j]
- 打开文件夹时,文件默认以列表查看方式浏览
- Flex Tree 的数据源从XML中读取
- cuda的PACK
- 数组,折腾折腾你。。。。
- 线性和相对布局的总结
- PowerVM 存储特性NPIV实例介绍
- 大赛计分
- dedeCMS的标签的使用