Leetcode1299. Replace Elements with Greatest Element on Right Side
Posted 一只桃子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode1299. Replace Elements with Greatest Element on Right Side相关的知识,希望对你有一定的参考价值。
public int[] replaceElements(int[] arr) {
for(int i=0;i<arr.length-1;i++)
arr[i]=findRightmax(i,arr);
arr[arr.length-1]=-1;
return arr;
}
public int findRightmax(int flag,int []nums){
int max=nums[flag+1];
for(int i=flag+1;i<nums.length;i++)
if(max<=nums[i]){
max=nums[i];
}
return max;
}
我的代码是不断去右边寻找最大值
这其中会有很多工作是重复的
Explanation
Iterate from the back to the start,
We initilize mx = 1
, where mx
represent the max on the right.
Each round, we set A[i] = mx
, where mx
is its mas on the right.
Also we update mx = max(mx, A[i])
, where A[i]
is its original value.
Complexity
Time O(N)
public int[] replaceElements(int[] A) {
for (int i = A.length - 1, mx = -1; i >= 0; --i)
mx = Math.max(A[i], A[i] = mx);//mx是A[i]右侧最大值,故每开始新的循环的时候,将当前值和后面的最大值比较,从而更新最大值,同时完成A[i]=mx,将当前值更新为后面最大值的操作
return A;
}
以上是关于Leetcode1299. Replace Elements with Greatest Element on Right Side的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode1299. Replace Elements with Greatest Element on Right Side
Leetcode 1299. Replace Elements with Greatest Element on Right Side
1299. Replace Elements with Greatest Element on Right Side
算法leetcode|1299. 将每个元素替换为右侧最大元素(rust和go)