LeetCode #109 Convert Sorted List to Binary Search Tree (有序链表转换为平衡二叉搜索树)

题目:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

分析:

给定一个有序链表,将其转换为一个高度平衡的二叉搜索树。

首先遍历链表获得链表长度。之后通过递归生成二叉搜索树。其生成过程和树的中序遍历类型:先是左子树,然后是根节点,最后是右子树。每添加一个树节点,就把链表节点的值赋给树节点,然后指针指向下一个链表节点。

Continue reading LeetCode #109 Convert Sorted List to Binary Search Tree (有序链表转换为平衡二叉搜索树)

LeetCode #128 Longest Consecutive Sequence

题目:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.

 

分析:

给定一个数组,求该数组中的数字所能构成的最长连续数列的长度。要求时间复杂度为O(n)。

我们使用HashMap。其中key为数组中的数字;value为该数字作为某个连续数列的边界时,该数列的长度。例如,对于数列{1,2,3,4,5},该数列的边界时1和5,那么在HashMap中1和5对应的value都是该数列的长度5。

当我们新读取一个数字时,该数字可能和其左侧或右侧的某个连续数列连接在一起。通过读取HashMap中 n-1 和 n+1 对应的value即可获得左侧和右侧连续数列的长度。之后将它们连接在一起,构成了一个新的更长的数列。最后将新数列边界元素的value更新为新的长度即可。

Continue reading LeetCode #128 Longest Consecutive Sequence