标签:desc def 插入排序 return describe 代码 小技巧 nim 节点
尝试着刷刷一些经典LeetCode题练练手感,随手做了两道看起来不起眼但还是需要一些细节的题:
class Solution { public: int run(TreeNode *root) { if( root == nullptr) return 0; int res_left = run(root->left); int res_right = run(root->right); if( !res_left) return res_right+1; if( !res_right) return res_left+1; return min(res_left,res_right)+1; //只有两端都有子树的时候返回最小值才有意义 } };
Sort a linked list using insertion sort.
真的是非常不起眼的一道题目,但是如果是一个新手还真不一定写得出来,链表还是需要一些小技巧的.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *insertionSortList(ListNode *head) { if(head == nullptr || head->next == nullptr) return head; ListNode *fake = new ListNode(INT_MIN); //多加入的一个节点,后续循环的时候会方便很多(trick) fake->next = head; ListNode *res = fake; ListNode *cur = head->next; head->next = nullptr; while(cur){ //2层while循环,O(n^2)时间复杂度的插入排序 ListNode * inspos = res; while(inspos->next){ if(inspos->next->val <= cur->val) inspos = inspos->next; else{ ListNode *temp = inspos->next; inspos->next = cur; cur = cur->next; inspos->next->next = temp; break; } } if(inspos->next == nullptr){//插入到末尾的特殊情况. inspos->next = cur; cur = cur->next; inspos->next->next = nullptr; } } return res->next; } };
LeetCode之 insertion-sort-list && insertion-sort-list
标签:desc def 插入排序 return describe 代码 小技巧 nim 节点
原文地址:https://www.cnblogs.com/J1ac/p/9438050.html