首页 > 其他 > 详细

【leetcode】1299. Replace Elements with Greatest Element on Right Side

时间:2019-12-29 09:40:36      阅读:75      评论:0      收藏:0      [点我收藏+]

题目如下:

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

解题思路:从右往左遍历arr,同时记录出现的最大值即可。

代码如下:

class Solution(object):
    def replaceElements(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        res = [-1]
        max_val = arr[-1]
        for i in range(len(arr)-2,-1,-1):
            res.insert(0,max_val)
            max_val = max(arr[i], max_val)
        return res

 

【leetcode】1299. Replace Elements with Greatest Element on Right Side

原文:https://www.cnblogs.com/seyjs/p/12114149.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!