티스토리 뷰
반응형
12일차 Last Stone Weight 입니다.
-문제 :
https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3297/
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together.
Suppose the stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed,
and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left.
Return the weight of this stone (or 0 if there are no stones left.)
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.
1 <= stones.length <= 30
1 <= stones[i] <= 1000
- 풀이 :
class Solution {
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
int count = stones.length-1;
while(count >= 1) {
int cal = stones[count] - stones[count-1];
if(cal == 0) {
stones[count--] = 0;
stones[count--] = 0;
}else {
stones[count--] = 0;
stones[count] = cal;
}
Arrays.sort(stones, 0, count+1);
}
return stones[0];
}
}
가장 큰 두 수를 빼고 남으면 다시 배열에 넣고 아니면 넣지 제거하는 문제입니다.
처음에는 다른 방식으로 생각해보았는데 이 방법이 가장 빠를 것 같아 풀어보니 통과했네요.
정렬과 stone의 계산된 수가 0일 때와 아닐 때를 구분하여 계산하는 방법입니다.
count와 stones를 정렬하는 방법으로 숫자가 한 개 남을 때까지 계산하는 방법입니다.
count는 stone의 개수를 저장하고 가장 무거운 스톤 두 개를 계산한 값이 0일 때와 아닐 때를 따로 계산합니다.
0이라면 두 수 모두 0으로 변경하고 아니라면 마지막 수만 0으로 다른 수는 두 수의 차를 저장합니다.
그리고 정렬을 다시 하고 반복합니다.
주어진 숫자가 1000가 최대 이기 때문에 시간 복잡도는 최대 O(n^2)이 아닐까 생각됩니다.
반응형
'알고리즘 > LeetCode 공부' 카테고리의 다른 글
[LeetCode] Java - Number Complement ( reverse binary ) (0) | 2020.05.04 |
---|---|
[LeetCode] Java - Maximal Square (0) | 2020.04.30 |
[Leet Code] Java - Counting Elements (0) | 2020.04.10 |
[LeetCode] Java - Group Anagrams (0) | 2020.04.08 |
[LeetCode] Java - Best Time to Buy and Sell Stock II (0) | 2020.04.07 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 지도학습
- LeetCode 30일 챌린지
- Java leetcode
- GPT서비스
- 에라토스테네스
- GPTGOT
- 파이썬
- 리엑트
- React 프로젝트 생성
- Python
- 30 Day LeetCode Challenge
- CHATGOT
- react
- Java
- Component
- 넘파이
- 퍼셉트론
- LeetCode 5월 챌린지
- git
- 파이썬 numpy
- LeetCode 풀이
- vscode
- 노드
- k8s metrics-server
- 머신러닝
- LeetCode 알고리즘 공부
- Node
- numpy
- k8s metrics-server running
- 버츄얼스튜디오코드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함