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;
    }
};

猜你喜欢

转载自www.cnblogs.com/J1ac/p/9438050.html