关键字
倒序遍历
题目描述
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
博主提交的代码
一坨屎就是
public int[] replaceElements(int[] arr) {
int[] result = new int[arr.length];
for(int i = 0; i < arr.length ;i++){
int now = arr[i];
if( i + 1 < arr.length ){
int max = arr[i + 1];
for(int j = i +1; j< arr.length; j++){
if( max< arr[j]){
max = arr[j];
}
}
result[i] = max;
} else{
result[i] = -1;
}
}
return result;
}
他人优秀的代码
public int[] replaceElements(int[] A) {
for (int i = A.length - 1, mx = -1; i >= 0; --i)
mx = Math.max(A[i], A[i] = mx);
return A;
}
扩展版
public int[] replaceElements2(int[] A) {
int mx = -1, n = A.length, a;
for (int i = n - 1; i >= 0; --i) {
a = A[i];
A[i] = mx;
mx = Math.max(mx, a);
}
return A;
}