- Replace With Greatest From Right
Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is [16, 17, 4, 3, 5, 2], then it should be modified to [17, 5, 5, 5, 2, -1].
Example
Example1
Input: nums = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 5, 5, 2, -1]
Example2
Input: nums = [16, 9, 12, 7, 6, 2]
Output: [12, 12, 7, 6, 2, -1]
解法1:
用一个数组存储每个元素后面的最大值就可以了。
class Solution {
public:
/**
* @param nums: An array of integers.
* @return: nothing
*/
void arrayReplaceWithGreatestFromRight(vector<int> &nums) {
int n = nums.size();
if (n == 0) return;
vector<int> revMaxes(n, INT_MIN);
for (int i = n - 2; i >= 0; --i) {
revMaxes[i] = max(revMaxes[i + 1], nums[i + 1]);
}
for (int i = 0; i < n - 1; ++i) {
nums[i] = revMaxes[i];
}
nums[n - 1] = -1;
}
};
1万+



被折叠的 条评论
为什么被折叠?



