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
Solution: Scan from right to left
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua class Solution { public: vector<int> replaceElements(vector<int>& arr) { int g = -1; for (int i = arr.size() - 1; i >= 0; --i) g = max(g, exchange(arr[i], g)); return arr; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment