1
-
2
1
/* *
3
2
* @file
4
3
* @brief find the length of the Longest Increasing Subsequence (LIS)
53
52
#include < iostream> // / for IO operations
54
53
#include < vector> // / for std::vector
55
54
#include < algorithm> // / for std::lower_bound
55
+ #include < cstdint> // / for std::uint32_t
56
56
57
57
/* *
58
58
* @brief Function to find the length of the Longest Increasing Subsequence (LIS)
59
59
* using Binary Search
60
- * @param nums The input vector of integers
60
+ * @tparam T The type of the elements in the input vector
61
+ * @param nums The input vector of elements of type T
61
62
* @return The length of the longest increasing subsequence
62
63
*/
63
- int longest_increasing_subsequence_using_binary_search (std::vector<int >& nums) {
64
+
65
+ template <typename T>
66
+ std::uint32_t longest_increasing_subsequence_using_binary_search (std::vector<T>& nums) {
64
67
if (nums.empty ()) return 0 ;
65
68
66
- std::vector<int > ans;
69
+ std::vector<T > ans;
67
70
ans.push_back (nums[0 ]);
68
- for (int i = 1 ; i < nums.size (); i++) {
71
+ for (std:: size_t i = 1 ; i < nums.size (); i++) {
69
72
if (nums[i] > ans.back ()) {
70
73
ans.push_back (nums[i]);
71
74
} else {
72
- int idx = std::lower_bound (ans.begin (), ans.end (), nums[i]) - ans.begin ();
75
+ auto idx = std::lower_bound (ans.begin (), ans.end (), nums[i]) - ans.begin ();
73
76
ans[idx] = nums[i];
74
77
}
75
78
}
76
- return ans.size ();
79
+ return static_cast <std:: uint32_t >( ans.size () );
77
80
}
78
81
79
82
/* *
@@ -93,8 +96,14 @@ static void tests() {
93
96
std::vector<int > arr4 = {-10 , -1 , -5 , 0 , 5 , 1 , 2 };
94
97
assert (longest_increasing_subsequence_using_binary_search (arr4) == 5 );
95
98
96
- std::vector<int > arr5 = {};
97
- assert (longest_increasing_subsequence_using_binary_search (arr5) == 0 );
99
+ std::vector<double > arr5 = {3.5 , 1.2 , 2.8 , 3.1 , 4.0 };
100
+ assert (longest_increasing_subsequence_using_binary_search (arr5) == 4 );
101
+
102
+ std::vector<char > arr6 = {' a' , ' b' , ' c' , ' a' , ' d' };
103
+ assert (longest_increasing_subsequence_using_binary_search (arr6) == 4 );
104
+
105
+ std::vector<int > arr7 = {};
106
+ assert (longest_increasing_subsequence_using_binary_search (arr7) == 0 );
98
107
99
108
std::cout << " All tests have successfully passed!\n " ;
100
109
}
0 commit comments