ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 1299. Replace Elements with Greatest Element on Right Side 将每个元素替换为右侧最大元素

2022-05-18 13:00:58  阅读:148  来源: 互联网

标签:index arr Elements -- 元素 element right greatest 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]
Explanation:
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.

Example 2:

Input: arr = [400]
Output: [-1]
Explanation: There are no elements to the right of index 0.

Constraints:

  • 1 <= arr.length <= 104
  • 1 <= arr[i] <= 105

这道题给了一个数组 arr,说是让把每个数字更新为其右边的数字中最大的一个,最后一个数字变为 -1。既然是一道 Easy 的题目,就不用担心解法会太复杂,一般都是较短的行数就能搞定的。让求每个数字右边的数字中最大的一个,当然不能每次都遍历右边所有的数字来找最大值,虽说是 Easy 题目,但最好也别这么暴力地解,多少还是要给 OJ 一些尊重的。从左往右不好使的话,可以调个头,从右往左去更新,这样就简单的多了,最后一个数字直接更新为 -1,然后只要维护一个从右往左的当前最大值,每次用来更新右往左的对应位置即可,基本没什么难度,只要能想到换个方向更新,基本就迎刃而解了,参见代码如下:


class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        int n = arr.size(), curMax = INT_MIN;
        vector<int> res(n, -1);
        for (int i = n - 2; i >= 0; --i) {
            curMax = max(curMax, arr[i + 1]);
            res[i] = curMax;
        }
        return res;
    }
};


Github 同步地址:

https://github.com/grandyang/leetcode/issues/1299


类似题目:

Two Furthest Houses With Different Colors


参考资料:

https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/

https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/463249/JavaC%2B%2BPython-Straight-Forward


LeetCode All in One 题目讲解汇总(持续更新中...)

标签:index,arr,Elements,--,元素,element,right,greatest,Side
来源: https://www.cnblogs.com/grandyang/p/16284279.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有