给一整数数组, 用当前元素之后数组中的最大元素来替换当前元素(右侧的最大元素). 因为最后一个元素的右边没有元素了, 所以用 -1
来替换这个值. 举个例子, 如果数组为 [16,17,4,3,5,2]
, 那么它就需要修改为 [17,5,5,5,2,-1]
.
样例
样例1
输入: nums = [16, 17, 4, 3, 5, 2]
输出: [17, 5, 5, 5, 2, -1]
样例2
输入: nums = [16, 9, 12, 7, 6, 2]
输出: [12, 12, 7, 6, 2, -1]
class Solution {
public:
/**
* @param nums: An array of integers.
* @return: nothing
*/
void arrayReplaceWithGreatestFromRight(vector<int> &nums) {
// Write your code here.
int tmpmax = INT_MIN;
for(int i = 1; i < nums.size(); i++)
{
tmpmax = max(tmpmax, nums[i]);
}
for(int i = 0; i < nums.size()-1; i++)
{
if(nums[i] == tmpmax)
{
tmpmax = INT_MIN;
for(int j = i + 1; j < nums.size(); j++)
{
tmpmax = max(tmpmax, nums[j]);
}
nums[i] = tmpmax;
}
else
{
nums[i] = tmpmax;
}
}
nums[nums.size()-1] = -1;
}
};