250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Last Stone Weight 본문
728x90
반응형
https://leetcode.com/problems/last-stone-weight/
Last Stone Weight - 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
오름차순 정렬을 이용.
stones의 길이가 1일때까지 반복.
stones를 오름차순으로 정렬한 후,
가장 뒤에 있는 두 개의 수를 각각 y, x에 저장한다.
만약 두 수가 같지 않다면 y - x 를 stones에 넣어주면 된다.
리턴값은 stones의 길이를 판단하여, 비어있다면 0, 그렇지 않다면 0번째 수를 리턴한다.
var lastStoneWeight = function(stones) {
while(stones.length > 1){
const length = stones.length;
stones.sort((a, b) => a - b);
const y = stones.pop();
const x = stones.pop();
if(x !== y){
stones.push(y - x);
}
}
return stones.length ? stones[0] : 0;
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Flatten a Multilevel Doubled Linked List (0) | 2022.04.12 |
---|---|
(Leet Code JS)Merge Nodes In Between Zeros (0) | 2022.04.11 |
(Leet Code JS)Find First and Last Position of Element in Sorted Array (0) | 2022.04.04 |
(Leet Code JS)Swapping Nodes in a Linked List (0) | 2022.04.04 |
(Leet Code JS)Path With Maximum Probability (0) | 2022.03.28 |