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
Give nums = [16, 17, 4, 3, 5, 2]
, change nums to [17, 5, 5, 5, 2, -1]
You should do it in place.
解法一:
1 class Solution { 2 public: 3 /* 4 * @param : An array of integers. 5 * @return: nothing 6 */ 7 void arrayReplaceWithGreatestFromRight(vector<int> &nums) { 8 int size = nums.size(); 9 int max = nums[size - 1]; 10 nums[size - 1] = -1; 11 12 for (int i = size - 2; i >= 0; --i) { 13 int temp = nums[i]; 14 nums[i] = max; 15 max = max > temp ? max : temp; 16 } 17 } 18 };
本题比较简单,就是从尾开始往前遍历处理。注意题目中的题意是某个元素右边所有元素中的最大值,而不涉及该元素和最大值之间再比较。