TreeviewCopyright © aleen42 all right reserved, powered by aleen42

1299. 将每个元素替换为右侧最大元素

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

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-22 09:30:44
 * @LastEditTime: 2020-08-22 09:31:02
 * @Description: https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side/
 * @FilePath: \leetcode-googtech\#1299. Replace Elements with Greatest Element on Right Side\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {
    public int[] replaceElements(int[] arr) {
        // 初始化最大值
        int max = -1; 
        // 从后往前遍历数组元素
        for(int i = arr.length - 1; i >= 0; i--) {
            // 定义一个临时变量用于跟踪最大值
            int temp = arr[i];
            // 将每个元素用它右边最大的元素替换
            arr[i] = max;
            // 若当前元素大于最大值则重新初始化最大值
            if(temp > max) {
                max = temp; 
            }
        }
        // 返回结果数组
        return arr; 
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-22 09:30:51
LastEditTime: 2020-08-22 09:31:23
Description: https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side/
FilePath: \leetcode-googtech\#1299. Replace Elements with Greatest Element on Right Side\Solution.py
WebSite: https://algorithm.show/
'''

class Solution(object):
    def replaceElements(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        # 判断数组是否为空
        if not arr: return 0
        # 初始化结果数组
        result = []
        # 从后往前遍历数组元素
        for i in range(len(arr) - 1):
            # 依次获取第i个下标元素之后的最大元素值,然后将其添加到结果数组中
            maxValue = max(arr[i+1:])
            result.append(maxValue)
        # 将-1作为结果数组的最后一个元素
        result.append(-1)
        # 返回结果数组
        return result
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""