Question
[LeetCode 112] Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Submission
1 | /** |
[LeetCode 112] Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
1 | /** |
[LeetCode 300] Given an unsorted array of integers, find the length of longest increasing subsequence.
Similar to [LeetCode 334], solve the question by using dynamic programming, and the algorithm run in $O(n^2)$ time and can be speed up to $O(nlogn)$ by using binary search.
The easiest solution which take $O(n^2)$ running time1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class Solution {
public int lengthOfLIS(int[] nums) {
int[] length = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
length[i] = 1;
}
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j] && length[j] + 1 > length[i]) {
length[i] = length[j] + 1;
}
}
}
int maxLength = 0;
for (int i = 0; i < length.length; i++) {
if (length[i] > maxLength) {
maxLength = length[i];
}
}
return maxLength;
}
}
By using binary search the running time can be reduced to $O(nlogn)$
1 | public class Solution { |
Using an addition array lastIndex
to store the index of the last elements of possible increasing subsequences in nums
, lastIndex[j]
representing the index of the smallest elements in nums
in the subsequences with length = j
. maxLength
will be used to mark the maximum length of the increasing subsequence in the current iteration.
When maxLength = 5
, this
i | lastIndex[i] | Representing Sequence |
---|---|---|
0 | - | - |
1 | 2 | 2 |
2 | 4 | 2, 3 |
3 | 5 | 2, 3, 7 |
5 | 6 | 2, 3, 6 |
For each iteration, we would like to know whether nums[i]
will generate a longer/better increasing subsequences. By using binary search, to find the maximum length l
of a subsequences where its last number is just smaller than nums[i]
, and because the last value of the sequence represented by lastIndex[l+1]
is less than the nums[i]
(i.e nums[lastIndex[l+1]] > nums[i]
), thus, it generate a better increasing subsequences with length = l+1
, and lastIndex[l+1]
will be updated. If l+1
is greater than the current maximun length, it indicates that a longer increasing subsequence can be found.
[LeetCode 334] Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Using dynamic programming, find if there exist increasing subsequence with length greater than or equal to 3
1 | public class Solution { |
[LeetCode 100] Given two binary trees, write a function to check if they are equal or not.
1 | /** |
[LeetCode 258] Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Find the digital root of any positive number. The solution appear periodically from 1 to 9.
1 | public class Solution { |