Problem:
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
Note: The length of given array won't exceed 10000.
思路:
Solution (C++):
vector<int> nextGreaterElements(vector<int>& nums) {
if (nums.empty()) return {};
int n = nums.size();
vector<int> res(n, 0);
for (int i = 0; i < n; ++i) {
int j = i+1;
for (j; j < i+n; ++j) {
if (nums[j%n] > nums[i]) { res[i] = nums[j%n]; break; }
}
if (j == i+n) res[i] = -1;
}
return res;
}
性能:
Runtime: 404 ms Memory Usage: 9.8 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
原文链接: https://www.cnblogs.com/dysjtu1995/p/12702621.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342243
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!