Leetcode - Uncrossed Lines
Leetcode - Count Servers that Communicate

Leetcode - Replace Elements with Greatest Element on Right Side

violet posted @ May 26, 2020 06:17:59 AM in 算法 with tags Algorithm Golang array , 224 阅读

https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-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]

 

func replaceElements(arr []int) []int {
    if len(arr) == 0 {
        return []int{}
    }
    max := arr[len(arr)-1]
    result := make([]int, len(arr))
    result[len(arr)-1] = -1
    for i := len(arr)-2; i >= 0; i-- {
        result[i] = max
        if arr[i] > max {
            max = arr[i]
        } 
    }
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter