[LeetCode] Replace Elements with Greatest Element on Right Side

준규·2023년 3월 18일

1.문제


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.


정수 배열 arr가 주어질 때 각 인덱스의 값을 현재 인덱스보다 오른쪽의 값들 중 최댓값으로 변경해서 리턴하는 문제이다.

배열의 가장 마지막 값은 -1로 변경하면 된다.


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 <= 10^4
1 <= arr[i] <= 10^5


2.풀이

  1. 배열을 뒤에서부터 거꾸로 순회한다.
  2. 초기 최대값을 배열의 가장 마지막 값으로 하고 배열의 가장 마지막 값을 -1로 변경한다.
  3. 순회하면서 현재 값을 임시 변수에 저장해 두고 현재 값을 지금까지의 최댓값으로 변경한다. 그 후 저장 해둔 현재 값과 최댓값을 비교해서 최댓값을 변경한다.

/**
 * @param {number[]} arr
 * @return {number[]}
 */
const replaceElements = function (arr) {
    // 초기 배열 내 최댓값을 저장한다.
  let maxValue = arr[arr.length - 1];
  // 배열의 마지막 값은 -1로 변경한다.
  arr[arr.length - 1] = -1;

  // 배열의 마지막에서 두번째부터 거꾸로 for문을 돈다
  for (let i = arr.length - 2; i >= 0; i--) {
    // 현재 값을 저장한다.
    let current = arr[i];
    // 현재 인덱스 배열 값을 maxValue로 변경한다.
    arr[i] = maxValue;

    // 현재 값과 maxValue 값을 비교해서 최댓값을 갱신한다.
    if (current > maxValue) {
      maxValue = current;
    }
  }

  return arr;
};

3.결과

profile
안녕하세요 :)

0개의 댓글