LeetCode之 insertion-sort-list insertion-sort-list
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之 insertion-sort-list insertion-sort-list
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
嘗試著刷刷一些經典LeetCode題練練手感,隨手做了兩道看起來不起眼但還是需要一些細節的題:
1. 題目描述
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. [思路]:以前碰到的基本上都是一些算二叉樹最長深度的,還真是第一次要求最低深度的,如果一模一樣套用前者的代碼會出現一個問題,就是有些一半節點的返回值會變成0,這里需要稍微修改一下判定長度的規則,葉子節點的判定是關鍵. 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; //只有兩端都有子樹的時候返回最小值才有意義 } };2. 題目描述
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;} };?
轉載于:https://www.cnblogs.com/J1ac/p/9438050.html
總結
以上是生活随笔為你收集整理的LeetCode之 insertion-sort-list insertion-sort-list的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IO编程
- 下一篇: WPF 4 日历控件(Calendar)