[LintCode] Replace With Greatest From Right
文章目录
Problem
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.
Solution
public class Solution {
/**
* @param nums: An array of integers.
* @return: nothing
*/
public void arrayReplaceWithGreatestFromRight(int[] nums) {
// Write your code here.
int n = nums.length-1;
int max = nums[n];
nums[n] = -1;
for (int i = n-1; i >= 0; i--) {
int cur = nums[i];
nums[i] = max;
max = Math.max(max, cur);
}
return;
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论