코딩테스트 공부
[LeetCode] 1299. Replace Elements with Greatest Element on Right Side - 자바스크립트 0617
codevil
2022. 6. 17. 11:21
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
Replace Elements with Greatest Element on Right Side - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주어진 arr에서, 본인의 오른쪽에 위치한 숫자중 가장 큰 숫자를 push하는 문제이다.
arr의 길이가 n개라면 return한 값의 arr도 n개가 나와야한다.
주의할 사항은, 값이 없으면 -1을 push해야한다. 이 문제에서 사용될 것은
1. for문 (arr를 기준으로)
2. Math.max ( 오른쪽에 있는 모든 것들)
3. 3항 연산자
이렇게 3개를 사용하였다
전체 풀이
var replaceElements = function (arr) {
const result = []
for (let i = 0; i < arr.length; i++) {
i !== arr.length - 1 ? result.push(Math.max(...arr.slice(i + 1))) : result.push(-1)
}
return result
};