Question description
1299. Replace each element with the largest element on the right - LeetCode
Give you an arrayarr
, please replace each element with the largest element on the right. If it is the last element, use-1
replace.
After completing all replacement operations, please return to this array.
Example 1:
enter:arr = [17,18,5,4,6,1] Output:[18,6,6,6,1,-1] explain: - Subscript 0 Elements --> 右侧最大元素是Subscript 1 Elements (18) - Subscript 1 Elements --> 右侧最大元素是Subscript 4 Elements (6) - Subscript 2 Elements --> 右侧最大元素是Subscript 4 Elements (6) - Subscript 3 Elements --> 右侧最大元素是Subscript 4 Elements (6) - Subscript 4 Elements --> 右侧最大元素是Subscript 5 Elements (1) - Subscript 5 Elements --> There are no other elements on the right,Replace with -1
Example 2:
enter:arr = [400] Output:[-1] explain:Subscript 0 There are no other elements on the right side of the element。
hint:
1 <= <= 10^4
1 <= arr[i] <= 10^5
Idea Analysis
It can be seen from the question
- If you traverse from right to left, you just look for the maximum value from the traversed numbers.
- If you traverse from left to right, you need to compare the values that have not been traversed in advance.
It is not difficult to see that traversing from right to left only requires O(n) time complexity.
traversal from left to right requires O(n^2) time complexity
I realized from this question that sometimes when you encounter difficulties in life, you might as well think about it with a different mindset
Perhaps the current difficulties are just a test for oneself
Spending more thinking to solve problems will save more time for subsequent implementation than using simple lazy thinking to solve problems
AC Code
class Solution { public int[] replaceElements(int[] arr) { int max = -1; for (int i = - 1; i >= 0; i--) { int tmp = arr[i]; arr[i] = max; if (tmp > max) { max = tmp; } } return arr; } }
Java 100% - Replace each element with the largest element on the right
Just reverse order traversal
Code
class Solution { public int[] replaceElements(int[] arr) { int max = -1; int[] ans = new int[]; for(int i = -1;i >= 0;i--){ int temp = arr[i]; ans[i] = max; max = (max,temp); } return ans; } }
traverse from right to left once - replace each element with the largest element on the right
Iterate from right to left, first record the maximum value rightMax on the right as the last value, and update rightMax to the left every time, use the variable t to remember the current arr[i] first.
class Solution { public int[] replaceElements(int[] arr) { int rightMax = arr[ - 1]; arr[ - 1] = -1; for (int i = - 2; i >= 0; i--) { int t = arr[i]; arr[i] = rightMax; if (t > rightMax) rightMax = t; } return arr; } }
The above is the detailed content of the go language problem LeetCode1299 replacing each element with the largest element on the right. For more information about replacing the largest element on the right of go elements, please pay attention to my other related articles!