148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
解析:
(1)方法一:快速排序。鏈表排序不同於數組,數組可以通過下標直接操作。但是思想可借鑑,下面借鑑快排的思想。將鏈表的頭節點作爲基準,將鏈表分爲左右兩條,左邊鏈表的所有節點都小於基準,右邊的所有節點都大於基準。然後再對兩條鏈表進行排序。時間複雜度爲O(nlogn)。
(2)方法二:合併排序。
C++代碼實現:
方法一:(LeetCode : 13/15 passed,超時)
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
int count = 0; //節點數量
ListNode* p = head;
while(p) {
count++;
p = p->next;
}
return quickSort(head,count);
}
private:
ListNode* quickSort(ListNode*& head,int count) {
if(count>1) {
int left = count;
ListNode* base = partition(head,left);
quickSort(head,left);
if(base!=head){
ListNode* leftEnd = head;
while(leftEnd->next!=base) {
leftEnd = leftEnd->next;
}
leftEnd->next = base;
}
if(base!=NULL && base->next!=NULL){
ListNode*temp = quickSort(base->next,count-left-1);
base->next = temp;
}
}
return head;
}
ListNode* partition(ListNode*& head,int& count) { //count代表head指向的鏈的節點數量
if(head==NULL || count<=1)
return head;
ListNode sNode(0), bNode(0);
ListNode* p1 = &sNode,*p2 = &bNode;
int key = head->val;
ListNode* base = head; //以第一個節點爲基準,將鏈表分爲兩條
int k = 0;
while(k<count && head) {
if(head->val < key)
p1 = p1->next = head;
else
p2 = p2->next = head;
head = head->next;
k++;
}
if(!head)
p2->next = NULL;
else
p2->next = head;
p1->next = bNode.next;
head = sNode.next;
p1 = head;
count = 0;
while(p1!=base && p1!=NULL){
count++;
p1 = p1->next;
}
return base;
}
};
179. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
C++代碼實現:
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> datas;
for(int a :nums)
datas.push_back(to_string(a));
sort(datas.begin(),datas.end(),[](string sa,string sb){
return (sa+sb)>(sb+sa);
});
string result;
for(string s : datas)
result = result + s;
return result[0]=='0' ? "0" : result;
}
};