Monthly Archives: February 2017

LeetCode Insertion Sort List

147. Insertion Sort List

Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.


Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

对一个链表进行插入排序。 简单题,每次从原链表中断一个节点下来,然后在新的有序链表中线性查找插入的位置。这里有个技巧,有可能链表的第一个节点很大,后续节点需要插入表头;也可能后续节点很大,需要插入表尾;还可能是不大不小,插入中间。情况比较多,为了方便统一代码形式,可以在新的有序链表的表头插入一个INT_MIN的最小节点,这样所有代码都统一了,也不容易出错。 完整代码如下:

class Solution {
public:
    ListNode* insertionSortList(ListNode* head)
    {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode* newHead = new ListNode(INT_MIN);
        newHead->next = head;
        head = head->next;
        newHead->next->next = NULL;
        while (head) {
            ListNode *insertPos = newHead->next, *pre = newHead;
            while (insertPos && insertPos->val < head->val) {
                insertPos = insertPos->next;
                pre = pre->next;
            }
            ListNode* tmp = head;
            head = head->next;
            tmp->next = insertPos;
            pre->next = tmp;
        }
        return newHead->next;
    }
};

本代码提交AC,用时59MS。

二刷。需要注意如果测试数据中含有INT_MIN的情况:

class Solution {
public:
	ListNode* insertionSortList(ListNode* head) {
		if (head == NULL || head->next == NULL)return head;
		ListNode *dummy = new ListNode(INT_MIN);
		ListNode *l1 = head, *l2 = head;
		while (l1 != NULL) {
			l2 = l1->next;

			ListNode *l3 = dummy, *l3_pre = dummy;
			while (l3 != NULL && l1->val > l3->val) {
				l3_pre = l3;
				l3 = l3->next;
			}
			if (l1->val == INT_MIN) {
				l1->next = dummy->next;
				dummy->next = l1;
			}
			else {
				l1->next = l3;
				l3_pre->next = l1;
			}

			l1 = l2;
		}
		return dummy->next;
	}
};

本代码提交AC,用时48MS。

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

本题要根据树的中序和后序遍历结果,重构出树的结构。 有了之前LeetCode Construct Binary Tree from Preorder and Inorder Traversal根据前序和中序重构树的算法,这一题就是照猫画虎了。因为后序遍历是最后一个数为根节点,和前序遍历其实没本质差别。找准inorder和postorder下标的起止位置就可以开始写代码了:

class Solution {
private:
    TreeNode* dfs(vector<int>& inorder, vector<int>& postorder, int inL, int inR, int postL, int postR, unordered_map<int, int>& hash)
    {
        if (inL > inR || postL > postR)
            return NULL;
        TreeNode* root = new TreeNode(postorder[postR]);
        int idx = hash[root->val];
        root->right = dfs(inorder, postorder, inL + 1, inR, postR – (inR – idx), postR – 1, hash);
        root->left = dfs(inorder, postorder, inL, idx – 1, postL, postR – (inR – idx) – 1, hash);
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        if (inorder.size() == 0)
            return NULL;
        unordered_map<int, int> hash;
        for (int i = 0; i < inorder.size(); ++i) {
            hash[inorder[i]] = i;
        }
        return dfs(inorder, postorder, 0, inorder.size() – 1, 0, postorder.size() – 1, hash);
    }
};

本代码提交AC,用时16MS。

LeetCode Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

根据树的先序遍历和中序遍历结果,重构这棵树。 其实大学的时候就有这样的作业,如果在纸上做,还是很简单的,但要实现成代码,稍微有点难理清这里的关系。 我们先来看一个纸上的解题过程,假设有下面这样一棵树:

        3
     /     \
    9       20
  /  \     /   \
 1    2  15    17
  • 先序遍历结果为:3, 9, 1, 2, 20, 15, 17
  • 中序遍历结果为:1, 9, 2, 3, 15, 20, 17

首先我们可以根据先序遍历结果找到根节点3,然后在中序遍历中看看3所处的位置,那么3左边的就是左孩子节点,右边的就是右孩子节点。我们在中序遍历中看看3左边有3个节点,说明3的左子树共有3个节点,同理右子树有3个节点。所以我们在先序遍历中也能知道3后面的3个节点是左子树,再后面3个节点是右子树,这样就把两个遍历结果分成了两部分:

  • 先序遍历结果为:3, 9, 1, 2, 20, 15, 17
  • 中序遍历结果为:1, 9, 2, 3, 15, 20, 17

在红色部分递归就是3的左子树,在蓝色部分递归就是3的右子树。 纸上解题好说,但是代码实现,我开始还把自己搞糊涂了,代码很复杂,后来参考了这位大神的博客,代码好简洁易懂,赞一个:

class Solution {
private:
    TreeNode* dfs(vector<int>& preorder, vector<int>& inorder, int preL, int preR, int inL, int inR, unordered_map<int, size_t>& hash)
    {
        if (preL > preR || inL > inR)
            return NULL;
        TreeNode* root = new TreeNode(preorder[preL]);
        size_t idx = hash[root->val];
        root->left = dfs(preorder, inorder, preL + 1, idx – inL + preL, inL, idx – 1, hash);
        root->right = dfs(preorder, inorder, idx – inL + preL + 1, preR, idx + 1, inR, hash);
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
    {
        if (preorder.size() == 0)
            return NULL;
        unordered_map<int, size_t> hash;
        for (size_t i = 0; i < inorder.size(); ++i) {
            hash[inorder[i]] = i;
        }
        return dfs(preorder, inorder, 0, preorder.size() – 1, 0, inorder.size() – 1, hash);
    }
};


本代码提交AC,用时16MS。
代码中有两点需要注意的,一是为了在中序遍历中快速找到根节点,提前对中序遍历结果hash了,因为题目中说了不会有重复元素;二是在dfs递归的时候,要算好下标的起止位置,一定不要弄错了,特别是preorder在左右子树中的起止位置。

LeetCode Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

本题还是树的层次遍历,但是稍微有点不一样,要求奇数层从左往右输出,偶数层从右往左输出。常规的层次遍历使用BFS实现,即队列,这里要求颠倒顺序,马上想到用堆栈。
维护一个left2right布尔变量,当tru时,把孩子从左往右压栈,这样下一层的输出顺序就是从右往左了;当为false时相反。这里我们还需要用到两个堆栈,分别保存当前层和下一层的结果。
talk is cheap, show you the code!

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode* root)
    {
        vector<vector<int> > ans;
        if (!root)
            return ans;
        bool left2right = true;
        stack<TreeNode*> stk;
        stk.push(root);
        while (!stk.empty()) {
            stack<TreeNode*> stk2;
            vector<int> cand;
            size_t n = stk.size();
            for (size_t i = 0; i < n; ++i) {
                TreeNode* top = stk.top();
                stk.pop();
                if (!top)
                    continue;
                cand.push_back(top->val);
                if (left2right) {
                    stk2.push(top->left);
                    stk2.push(top->right);
                }
                else {
                    stk2.push(top->right);
                    stk2.push(top->left);
                }
            }
            left2right = !left2right;
            if (!cand.empty())
                ans.push_back(cand);
            stk = stk2;
        }
        return ans;
    }
};

本代码提交AC,用时6MS。

二刷。不使用两个栈,而使用一个双端队列也可以:

class Solution {
public:
	vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
		vector<vector<int>> ans;
		if (root == NULL)return ans;
		deque<TreeNode*> q;
		q.push_back(root);
		bool left2right = true;
		while (!q.empty()) {
			vector<int> cur;
			if (left2right) {
				int n = q.size();
				for (int i = 0; i < n; ++i) {
					cur.push_back(q[i]->val);
				}
				ans.push_back(cur);
				for (int i = n - 1; i >= 0; --i) {
					TreeNode* tn = q.back();
					q.pop_back();
					if (tn->right)q.push_front(tn->right);
					if (tn->left)q.push_front(tn->left);
				}
				left2right = false;
			}
			else {
				int n = q.size();
				for (int i = n - 1; i >= 0; --i) {
					cur.push_back(q[i]->val);
				}
				ans.push_back(cur);
				for (int i = 0; i < n; ++i) {
					TreeNode* tn = q.front();
					q.pop_front();
					if (tn->left)q.push_back(tn->left);
					if (tn->right)q.push_back(tn->right);
				}
				left2right = true;
			}
		}
		return ans;
	}
};

本代码提交AC,用时4MS。

LeetCode Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

Example 2:

Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Reference of the node with value = 2
Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

Example 3:

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

给定两个链表,如果这两个链表在某个点相交,并且此后合并为一个链表,要找出这个交点;如果不想交,返回NULL。 简单的方法是,如果两个链表相交,比如题图在c1相交,则对于两个链表,从相交点往后长度是一样的,所以我们可以先求出两个链表的长度,假设长度差是delta,则较长链表先前进delta步,此时长短链表的往后的路都是一样长了,这样两个链表一起走,如果发现有相等的节点,则是相交节点,否则两个链表不相交。 本思路代码如下:

class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
    {
        int len1 = 0, len2 = 0;
        ListNode *h1 = headA, *h2 = headB;
        while (h1) {
            ++len1;
            h1 = h1->next;
        }
        while (h2) {
            ++len2;
            h2 = h2->next;
        }
        h1 = headA;
        h2 = headB;
        if (len1 > len2) {
            while (len1 > len2) {
                h1 = h1->next;
                –len1;
            }
        }
        else if (len2 > len1) {
            while (len2 > len1) {
                h2 = h2->next;
                –len2;
            }
        }
        while (h1 && h2 && h1 != h2) {
            h1 = h1->next;
            h2 = h2->next;
        }
        if (!h1 || !h2)
            return NULL;
        else
            return h1;
    }
};

本代码提交AC,用时39MS。
还有一种思路很巧妙,参考:http://www.cnblogs.com/yuzhangcmu/p/4128794.html
具体是这样的,比如题目中的例子,假设指针pA和pB分别指向A,B两个链表,两个指针同时不断的一步一步走,当pA走到结尾时,pA指向B链表表头开始走,同理当pB走到结尾时,pB指向A链表表头开始走。不断的走,当pA和pB指向同一个节点时,就是那个相交的节点。这个很巧妙呀,当pA和pB走到相交点时,他们走过的路程其实是相等的,比如题目中,他们都走了9个节点后相遇了。
代码如下:

class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
    {
        if (headA == NULL || headB == NULL)
            return NULL;
        ListNode *h1 = headA, *h2 = headB;
        ListNode *tail1 = NULL, *tail2 = NULL;
        while (true) {
            if (h1 == NULL)
                h1 = headB;
            if (h2 == NULL)
                h2 = headA;
            if (h1->next == NULL)
                tail1 = h1;
            if (h2->next == NULL)
                tail2 = h2;
            if (tail1 != NULL && tail2 != NULL && tail1 != tail2)
                return NULL;
            if (h1 == h2)
                return h1;
            h1 = h1->next;
            h2 = h2->next;
        }
    }
};

本代码提交AC,用时36MS。

三刷。同样的思路:

class Solution {
public:
	ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
		if (headA == NULL || headB == NULL)return NULL;
		ListNode *la = headA, *lb = headB;
		bool la_changed = false, lb_changed = false;
		while (la != lb) {
			la = la->next;
			lb = lb->next;
			if (la == NULL) {
				if (la_changed)return NULL;
				else {
					la = headB;
					la_changed = true;
				}
			}
			if (lb == NULL) {
				if (lb_changed)return NULL;
				else {
					lb = headA;
					lb_changed = true;
				}
			}
		}
		return la;
	}
};

本代码提交AC,用时68MS。

LeetCode Word Ladder

127. Word Ladder

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possibletransformation.

很有意思的一个题。给定两个单词beginWord和endWord,以及一个字典数组,问从beginWord到endWord,最少需要多少次变换,每次只能变换一个字母,而且变换的单词都必须存在于字典数组中。

很明显是一个BFS题,从beginWord开始广搜,直到第一次搜到endWord时停止,此时走过的变换数就是最小变换数。因为广搜会搜索所有的空间,那么第一次到达endWord也就是最早到达的。
当然BFS的题也都能用DFS来做,但是DFS显然会慢,想想便知,DFS必须搜索完一条完整的路径才能知道结果,才能进入下一条路径开始搜索;而BFS是每条路径同步进行,只要有一条路径到达,就结束搜索。
常规的BFS代码如下:

typedef struct Item {
    string cur;
    string used;
    int step;
    Item(string c, string u, int s)
        : cur(c)
        , used(u)
        , step(s){};
};
class Solution {
public:
    bool differOne(const string& s1, const string& s2)
    {
        int cnt = 0;
        for (size_t i = 0; i < s1.size(); ++i) {
            if (s1[i] != s2[i]) {
                ++cnt;
                if (cnt > 1)
                    return false;
            }
        }
        return cnt == 1;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        size_t n = wordList.size();
        queue<Item> q;
        Item it(beginWord, string(n, ‘0’), 1);
        q.push(it);
        while (!q.empty()) {
            Item t = q.front();
            q.pop();
            if (t.cur == endWord)
                return t.step;
            for (size_t i = 0; i < n; ++i) {
                if (t.used[i] == ‘0’&& differOne(t.cur, wordList[i])) {
                    string newUsed = t.used;
                    newUsed[i] = ‘1’;
                    Item tmp(wordList[i], newUsed, t.step + 1);
                    q.push(tmp);
                }
            }
        }
        return 0;
    }
};

本代码很好理解,定义一个结构体Item,cur为当前到达的单词,用一个和wordList大小相同的字符串used表示走到cur时走过的单词,step表示当前走过的步数。很可惜,这个版本的代码提交MLE,超空间了。肯定是因为Item这个结构体太大了,两个string,一个int。

后来想到一个优化的方法,当某条路径path1走到单词cur时,其他路径就没必要再经过cur了,因为一旦经过cur,必定后续步骤和path1后续要走的路径就相同了,造成了重复搜索。所以我们走过每个单词时,可以直接将该单词置空,这样后续就不会再走该路了,同时这样也不需要Item结构体了。新版代码如下:

class Solution {
public:
    bool differOne(const string& s1, const string& s2)
    {
        int cnt = 0;
        for (size_t i = 0; i < s1.size(); ++i) {
            if (s1[i] != s2[i]) {
                ++cnt;
                if (cnt > 1)
                    return false;
            }
        }
        return cnt == 1;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        size_t n = wordList.size();
        queue<string> q;
        q.push(beginWord);
        int step = 1;
        while (!q.empty()) {
            size_t len = q.size();
            for (size_t i = 0; i < len; ++i) {
                string t = q.front();
                q.pop();
                if (t == endWord)
                    return step;
                for (size_t j = 0; j < wordList.size(); ++j) {
                    if (wordList[j] != "" && differOne(t, wordList[j])) {
                        q.push(wordList[j]);
                        wordList[j] = "";
                    }
                }
            }
            ++step;
        }
        return 0;
    }
};

本代码提交AC,用时632MS。

二刷。设置一个visited数组也许是更常规的做法:

class Solution {
public:
	bool IsConnect(const string &a, const string &b) {
		int diff = 0, n = a.size();
		for (int i = 0; i < n; ++i) {
			if (a[i] != b[i]) {
				++diff;
				if (diff > 1)return false;
			}
		}
		return diff == 1;
	}
	int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
		int n = wordList.size();
		if (n == 0)return 0;

		vector<int> visited(n, 0);
		queue<string> q;
		q.push(beginWord);
		int ans = 0;
		while (!q.empty()) {
			++ans;
			int m = q.size();
			for (int i = 0; i < m; ++i) {
				string cur = q.front();
				if (cur == endWord)return ans;
				q.pop();
				for (int j = 0; j < n; ++j) {
					if (visited[j] == 0 && IsConnect(cur, wordList[j])) {
						visited[j] = 1;
						q.push(wordList[j]);
					}
				}
			}
		}
		return 0;
	}
};

本代码提交AC,用时532MS。

LeetCode Word Search

79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

给定一个字符面板和一个单词,问能否在该面板中搜索到该单词,搜索路径只能水平或垂直。 简单的深度搜索题,首先找到第一个字符的起始位置,然后深度往该字符的上下左右搜,只要有一个true就返回true,否则重置标记位,返回false。 完整代码如下:

class Solution {
private:
    bool dfs(vector<vector<char> >& board, vector<vector<char> >& mark, int row, int col, string& word, int step)
    {
        if (board[row][col] != word[step])
            return false;
        if (step == word.size() – 1)
            return true;
        mark[row][col] = 1;
        if (row – 1 >= 0 && mark[row – 1][col] == 0) {
            bool ans = dfs(board, mark, row – 1, col, word, step + 1);
            if (ans)
                return true;
        }
        if (row + 1 < board.size() && mark[row + 1][col] == 0) {
            bool ans = dfs(board, mark, row + 1, col, word, step + 1);
            if (ans)
                return true;
        }
        if (col – 1 >= 0 && mark[row][col – 1] == 0) {
            bool ans = dfs(board, mark, row, col – 1, word, step + 1);
            if (ans)
                return true;
        }
        if (col + 1 < board[0].size() && mark[row][col + 1] == 0) {
            bool ans = dfs(board, mark, row, col + 1, word, step + 1);
            if (ans)
                return true;
        }
        mark[row][col] = 0;
        return false;
    }
public:
    bool exist(vector<vector<char> >& board, string word)
    {
        if (word.size() == 0)
            return true;
        int m = board.size();
        if (m == 0)
            return false;
        int n = board[0].size();
        if (n == 0)
            return false;
        vector<vector<char> > mark(m, vector<char>(n, 0));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] == word[0] && dfs(board, mark, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }
};

本代码提交AC,用时9MS,击败95.63%的人。

LeetCode Insert Interval

57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.


一个已经排好序的区间数组,现在要插入一个新的区间,并且如果能合并则需要合并。最简单的方法就是把新加入的区间和原有区间一起排个序,然后统一合并,问题就转换为LeetCode Merge Intervals了。

但是原有区间数组是已经按start排序了,所以有更简单的办法。我们可以分三个过程插入新的区间,首先把明显小于新区间的区间放到结果数组中,然后处理所有可能和新区间有overlap的区间,不断合并并更新新区间,直到无法再合并时,把新区间加入结果数组中,最后把明显大于新区间的区间放到结果数组中。

完整代码如下:

class Solution {
public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval)
    {
        vector<Interval> ans;
        int i = 0, n = intervals.size();
        while (i < n && intervals[i].end < newInterval.start)
            ans.push_back(intervals[i++]);
        while (i < n && newInterval.end >= intervals[i].start) {
            newInterval.start = min(newInterval.start, intervals[i].start);
            newInterval.end = max(newInterval.end, intervals[i].end);
            ++i;
        }
        ans.push_back(newInterval);
        while (i < n)
            ans.push_back(intervals[i++]);
        return ans;
    }
};

本代码提交AC,用时13MS。

LeetCode Merge Intervals

56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.


给定一个区间数组,也就是数组中保存的是一个个的区间[s,t],要求把数组中所有有overlap的区间合并起来。
简单题,先给数组排个序,然后只要看相邻的两个区间是否有重复就好了。排序的规则是先比较start,如果start相等,再比较end。
其实这个区间完全可以用pair来存,但是题目用一个自定义的Interval结构体存储。有两种方法可以对自定义结构体(或类)排序,一是重载Interval的小于<比较运算符,这样就可以直接sort(vector.begin(),vector.end())了,但是这样改变了Interval;还有一种方法是不改变Interval,自定义一个comp比较函数,传递给sort算法的第三个参数。
代码如下:

bool comp(const Interval& i, const Interval& j)
{
    return (i.start < j.start) || ((i.start == j.start) && (i.end < j.end));
}
class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals)
    {
        if (intervals.size() == 0)
            return vector<Interval>();
        sort(intervals.begin(), intervals.end(), comp);
        vector<Interval> ans = { intervals[0] };
        for (int i = 1; i < intervals.size(); ++i) {
            if (intervals[i].start <= ans.back().end) {
                ans.back().end = max(ans.back().end, intervals[i].end);
            }
            else {
                ans.push_back(intervals[i]);
            }
        }
        return ans;
    }
};

本代码提交AC,用时12MS。

二刷。想到用栈来合并区间,代码如下:

class Solution {
public:
	bool IsOverlap(const pair<int, int>& interval1, const pair<int, int>& interval2) {
		return interval1.second >= interval2.first;
	}
	vector<vector<int>> merge(vector<vector<int>>& intervals) {
		vector<pair<int, int>> intervals2;
		for (int i = 0; i < intervals.size(); ++i) {
			intervals2.push_back(make_pair(intervals[i][0], intervals[i][1]));
		}
		sort(intervals2.begin(), intervals2.end());
		vector<vector<int>> ans;
		stack<pair<int, int>> stk;
		for (int i = 0; i < intervals2.size(); ++i) {
			if (stk.empty()) {
				stk.push(intervals2[i]);
			}
			else {
				pair<int, int> top = stk.top();
				stk.pop();
				if (IsOverlap(top, intervals2[i])) {
					stk.push(make_pair(top.first, max(top.second, intervals2[i].second)));
				}
				else {
					ans.push_back({ top.first,top.second });
					stk.push({ intervals2[i].first,intervals2[i].second });
				}
			}
		}
		if (!stk.empty())ans.push_back({ stk.top().first,stk.top().second });
		return ans;
	}
};

本代码提交AC,用时24MS,效率不如第一种方法高。

LeetCode Jump Game II

45. Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.


上一题是问能否跳到数组右边,本题问最少需要多少跳能跳到数组右边,第一反应是DP。
设dp[i]表示从位置i跳到数组右边最少需要的跳数,则dp[n-1]=0,dp[0]就是最终结果。此时我们需要从数组右边往左边遍历,假设dp[i+1,…,n-1]都求出来了,现在要求dp[i]。站在位置i,我们最远能跳到i+A[i],所以我们就看看从i跳到哪个$j\in[i,i+A[i]]$能获得最少的跳数,从i跳到j需要增加一跳,所以递推式就是$dp[i]=min\{dp[j]+1\},\quad j\in[i+1,i+A[i]]$

这种思路的代码如下:

class Solution {
public:
    int jump(vector<int>& nums)
    {
        int n = nums.size();
        if (n <= 1)
            return 0;
        int maxJump = n – 1;
        vector<int> dp(n, 0);
        for (int i = n – 2; i >= 0; –i) {
            int curMinJump = maxJump;
            for (int j = i + 1; j <= nums[i] + i && j < n; ++j) {
                curMinJump = min(curMinJump, dp[j] + 1);
            }
            dp[i] = curMinJump;
        }
        return dp[0];
    }
};

可惜,本代码提交TLE,在最后一个大数据集上超时了。但是我还是觉得DP方法是一个基本法,而且如果要求出最小跳的路径,也很方便,如下代码,打印的时候,从pre[n-1]不断找前驱位置就好。

class Solution {
public:
    int jump(vector<int>& nums)
    {
        int n = nums.size();
        if (n <= 1)
            return 0;
        int maxJump = n – 1;
        vector<int> dp(n, 0), pre(n, 0);
        for (int i = n – 2; i >= 0; –i) {
            int curMinJump = maxJump, k = 0;
            for (int j = i + 1; j <= nums[i] + i && j < n; ++j) {
                if (dp[j] + 1 < curMinJump) {
                    curMinJump = dp[j] + 1;
                    k = j;
                }
            }
            dp[i] = curMinJump;
            pre[k] = i; // 从i跳到k能获得最小跳数
        }
        return dp[0];
    }
};

讨论区看到一个O(n)的解法,很厉害。思路和上一题LeetCode Jump Game很类似,依旧维护一个当前能跳到的最远位置curFarthest,同时维护一个当前跳能跳到的范围[curBegin, curEnd],一旦i超过了curEnd,说明应该开启下一跳了,同时更新curFarthest。

这种算法的思路很巧妙,他不管你当前跳到底跳到哪里,只管你能够跳到的范围,一旦走出这个范围,就必须开启下一跳了。代码如下:

class Solution {
public:
    int jump(vector<int>& nums)
    {
        int jumps = 0, curEnd = 0, curFarthest = 0;
        for (int i = 0; i < nums.size() – 1; ++i) {
            curFarthest = max(curFarthest, i + nums[i]);
            if (i == curEnd) {
                curEnd = curFarthest;
                ++jumps;
                if (curEnd >= nums.size() – 1)
                    break;
            }
        }
        return jumps;
    }
};

本代码提交AC,用时22MS。第10行是增加的提前结束的代码。
参考:

二刷。这题很有意思,时隔三年再刷此题,依然不会。首先想到的依然是DP的解法,不过这个DP比以前写的DP好理解一些,代码如下。思想就是steps[i]保存了要跳到i位置最小的步数,则初始时steps[0]=0,其他位置都是无穷大。然后,对于每个位置i,更新它能跳到的所有target位置的最小步数。最后返回steps[n-1]。

class Solution {
public:
	int jump(vector<int>& nums) {
		int n = nums.size();
		vector<int> steps(n, INT_MAX);
		steps[0] = 0;
		for (int i = 0; i < n; ++i) {
			for (int j = 1; j <= nums[i]; ++j) {
				int target = i + j;
				if (target < n) {
					steps[target] = min(steps[target], steps[i] + 1);
				}
				else {
					break;
				}
			}
		}
		return steps[n - 1];
	}
};

同样,DP解法在最后一个样例上TLE了。

评论区看到另一个O(n)的解法,比之前的更好理解: https://leetcode.com/problems/jump-game-ii/discuss/18028/O(n)-BFS-solution。这个解法把该问题想象为一个BFS层次遍历的问题。

以输入样例s=[2,3,1,1,4]为例,最开始我们在起点s[0],它最多能跳2步,所以能跳到s[1]和s[2]的位置,即3,1在BFS的同一层。s[1]=3能跳到除了该层的s[3]和s[4],即1,4在BFS的下一层;s[2]=1无法跳出第二层。因为4在最后一层,也就是第3层,所以最少可以2步到达。

2
3,1
1,4

代码如下:

class Solution {
public:
	int jump(vector<int>& nums) {
		int level = 0, current_fastest = 0, next_fastest = 0;
		int n = nums.size(), i = 0;
		if (n == 1)return 0;
		while (true) {
			++level;
			while (i <= current_fastest && i < n) {
				next_fastest = max(next_fastest, i + nums[i]);
				++i;
			}
			if (next_fastest >= n - 1)return level;
			current_fastest = next_fastest;
		}
		return 0;
	}
};

本代码提交AC,用时8MS。由于i指针一直在往前走,所以时间复杂度为O(n)。

三刷。 依然是BFS的思路,代码简洁易懂:

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        int step = 0, pre_max = 0, next_max = 0;
        for(int i = 0; i < n; ++i) {
            if(i > pre_max) {
                ++step;
                pre_max = next_max;
            } 
            next_max = max(next_max, i + nums[i]);
        }
        return step;
    }
};

本代码提交AC,用时28MS。