File tree Expand file tree Collapse file tree 3 files changed +68
-0
lines changed
0300_longest_increasing_subsequence Expand file tree Collapse file tree 3 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O1 -o test lis.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+
5+ static int binary_search (int * nums , int lo , int hi , int target )
6+ {
7+ while (lo + 1 < hi ) {
8+ int mid = lo + (hi - lo ) / 2 ;
9+ if (nums [mid ] < target ) {
10+ lo = mid ;
11+ } else {
12+ hi = mid ;
13+ }
14+ }
15+ return hi ;
16+ }
17+
18+ int lengthOfLIS (int * nums , int numsSize ){
19+ int i , piles = 0 ;
20+ int * tops = malloc (numsSize * sizeof (int ));
21+ for (i = 0 ; i < numsSize ; i ++ ) {
22+ int pos = binary_search (tops , -1 , piles , nums [i ]);
23+ if (pos == piles ) {
24+ piles ++ ;
25+ }
26+ tops [pos ] = nums [i ];
27+ }
28+ return piles ;
29+ }
30+
31+ int main (int argc , char * * argv )
32+ {
33+ int i ;
34+ int * nums = malloc ((argc - 1 ) * sizeof (int ));
35+ for (i = 0 ; i < argc - 1 ; i ++ ) {
36+ nums [i ] = atoi (argv [i + 1 ]);
37+ }
38+
39+ printf ("%d\n" , lengthOfLIS (nums , argc - 1 ));
40+ return 0 ;
41+ }
Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+
3+ using namespace std ;
4+
5+ class Solution {
6+ public:
7+ int lengthOfLIS (vector<int >& nums) {
8+ vector<int > dp (nums.size (), 1 );
9+ for (int i = 0 ; i < nums.size (); i++) {
10+ for (int j = 0 ; j < i; j++) {
11+ if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) {
12+ dp[i] = dp[j] + 1 ;
13+ }
14+ }
15+ }
16+
17+ int res = 0 ;
18+ for (int i : dp) {
19+ if (i > res) {
20+ res = i;
21+ }
22+ }
23+ return res;
24+ }
25+ };
You can’t perform that action at this time.
0 commit comments