标签:xpl flag htm rom key public origin elements math
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;
}
我的代码是不断去右边寻找最大值
这其中会有很多工作是重复的
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.
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
标签:xpl flag htm rom key public origin elements math
原文地址:https://www.cnblogs.com/chengxian/p/12207602.html