Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit da85c4f

Browse files
committed
"Longest Increasing Subsequence": new method
1 parent fdff12a commit da85c4f

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

‎src/300.c

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
#include <stdlib.h>
33
#include <assert.h>
44

5-
int lengthOfLIS(int* nums, int numsSize) {
5+
/* Dynamic Programming, O(n*n) */
6+
int lengthOfLIS0(int* nums, int numsSize) {
67
if (nums == NULL || numsSize == 0) return 0;
78
int *dp = (int *)malloc(numsSize * sizeof(int));
89
int i, j;
@@ -17,9 +18,39 @@ int lengthOfLIS(int* nums, int numsSize) {
1718
if (v > max)
1819
max = v;
1920
}
21+
free(dp);
2022
return max;
2123
}
2224

25+
/* Trace the LIS using an array and use binary search, O(nlogn) */
26+
int lengthOfLIS(int* nums, int numsSize) {
27+
if (nums == NULL || numsSize == 0) return 0;
28+
int *lis = (int *)malloc(numsSize * sizeof(int));
29+
lis[0] = nums[0];
30+
int len = 1;
31+
int i;
32+
for (i = 1; i < numsSize; i++) {
33+
if (nums[i] > lis[len - 1]) {
34+
lis[len++] = nums[i];
35+
}
36+
else {
37+
int l = 0, r = len - 1;
38+
while (l < r) {
39+
int m = l + (r - l) / 2;
40+
if (lis[m] >= nums[i]) {
41+
r = m;
42+
}
43+
else {
44+
l = m + 1;
45+
}
46+
}
47+
lis[l] = nums[i];
48+
}
49+
}
50+
free(lis);
51+
return len;
52+
}
53+
2354
int main() {
2455
int nums0[] = { 10, 9, 2, 5, 3, 7, 101, 18 };
2556
int nums1[] = { 1, 0, 1, 1 };

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /