作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
极点:数组中左侧元素小于或等于它且右侧元素大于或等于它的元素。
示例输入
3,1,4,5,9,7,6,11
期望的输出
4,5,11
面试时被问到这个问题,要返回元素的索引,只返回第一个满足条件的元素。
我的逻辑
- Take two MultiSet (So that we can consider duplicate as well), one for right hand side of the element and one for left hand side of the element(the pole).
- Start with 0th element and put rest all elements in the "right set".
- Base condition if this 0th element is lesser or equal to all element on "right set" then return its index.
- Else put this into "left set" and start with element at index 1.
- Traverse the Array and each time pick the maximum value from "left set" and minimum value from "right set" and compare.
- At any instant of time for any element all the value to its left are in the "left set" and value to its right are in the "right set"
代码
int magnitudePole (const vector<int> &A) {
multiset<int> left, right;
int left_max, right_min;
int size = A.size();
for (int i = 1; i < size; ++i)
right.insert(A[i]);
right_min = *(right.begin());
if(A[0] <= right_min)
return 0;
left.insert(A[0]);
for (int i = 1; i < size; ++i) {
right.erase(right.find(A[i]));
left_max = *(--left.end());
if (right.size() > 0)
right_min = *(right.begin());
if (A[i] > left_max && A[i] <= right_min)
return i;
else
left.insert(A[i]);
}
return -1;
}
我的问题
- I was told that my logic is incorrect, I am not able to understand why this logic is incorrect (though I have checked for some cases and it is returning right index)
- For my own curiosity how to do this without using any set/multiset in O(n) time.
最佳答案
对于 O(n) 算法:
你的代码(至少)在这里是错误的:
if (A[i] > left_max && A[i] <= right_min) // <-- should be >= and <=
关于algorithm - 面试 - 在数组中查找幅度极点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15397637/
我正在尝试在我的一个新项目中使用 WhirlyGlobe-Maply 的二进制库。图书馆可以在这里找到:http://mousebird.github.io/WhirlyGlobe/ WhirlyGl
我是一名优秀的程序员,十分优秀!