본문 바로가기
Computer Science/알고리즘

leetcode 148) Sort List

by eeeun:) 2022. 2. 24.
반응형

LV. Medium 🧐

https://leetcode.com/problems/sort-list/

 

Sort List - 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

 

문제

Given the head of a linked list, return the list after sorting it in ascending order.

 

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 * 10^4].
  • -10^5 <= Node.val <= 10^5

 

문제 해결법

vector<int> num_list를 둬서 ListNode를 한번 돌면서 val 값을 다 저장한다.

num_list를 정렬하고 다시 ListNode를 한번 돌면서 val 값을 정렬된 수로 업데이트해준다.

시간 복잡도는 sort을 써서 nlogn이다.

 

해결 코드
class Solution {
public:
	ListNode* sortList(ListNode* head) {
		vector<int> num_list;
		ListNode *temp = head;

		while(temp) {
			num_list.push_back(temp->val);
			temp = temp->next;
		}
		sort(num_list.begin(), num_list.end());
		int i = 0;
		temp = head;

		while(temp) {
			temp->val = num_list[i++];
			temp = temp->next;
		}
		return head;
	}
};

728x90

'Computer Science > 알고리즘' 카테고리의 다른 글

leetcode 228) Summary Ranges  (0) 2022.02.28
leetcode 165) Compare Version Numbers  (0) 2022.02.25
leetcode 133) Clone Graph  (0) 2022.02.23
leetcode 171) Excel Sheet Column Number  (0) 2022.02.22
leetcode 169) Majority Element  (0) 2022.02.21

댓글