반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- java 버전 변경
- Medium
- maybe not public or not valid?
- parse
- yum install java
- JUnit
- java 11
- querydsl no sources given
- no sources given
- aws
- java
- mac os git error
- No tests found for given includes
- java 여러개 버전
- AWS CLI
- error
- easy
- Java 1.8
- java version
- springboottest
- LeetCode
- el1008e
- 스프링부트테스트
- xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)
- log error
- springbatch error
- OpenFeign
- java 1.8 11
- property or field 'jobparameters' cannot be found on object of type
- springboot
Archives
- Today
- Total
쩨이엠 개발 블로그
[ Leetcode ] 148. Sort List - Java 본문
728x90
반응형
Given the head of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is in the range [0, 5 * 104].
- -105 <= Node.val <= 105
Solution
import java.util.*;
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
Collections.sort(list, Collections.reverseOrder());
ListNode answer = new ListNode(list.get(0));
for(int i=1; i< list.size(); i++){
answer = new ListNode(list.get(i), answer);
}
return answer;
}
}
1. ListNode가 null이거나 1개인 경우는 그대로 리턴한다
2. 값을 다 빼고 내림차순으로 sort한다
3. 첫번째부터 채워서 ListNode를 만들어준다
대체 더 빠르게는 어떻게 하는거지... 좀더 고민해보기
728x90
반응형
'개발 > Programming' 카테고리의 다른 글
[ Leetcode ] 6. ZigZag Conversion - Java (0) | 2021.02.25 |
---|---|
[ Leetcode ] 1669. Merge In Between Linked Lists - Java (0) | 2021.02.13 |
[ Leetcode ] 324. Wiggle Sort II - Java (0) | 2021.02.08 |
[ Leetcode ] 1561. Maximum Number of Coins You Can Get - Java (0) | 2021.02.07 |
[ Leetcode ] 763. Partition Labels - Java (0) | 2021.02.03 |
Comments