diff options
author | crupest <crupest@outlook.com> | 2020-05-15 17:01:47 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-05-15 17:01:47 +0800 |
commit | 1fa40aa140c7588b949196f4a13d99e37e5eacfd (patch) | |
tree | 7695c1974e3e4002d8bb084246afc02177c6dad5 | |
parent | d2e1594b39a4d25081b8e24dad77f8b86f7f3b47 (diff) | |
download | crupest-1fa40aa140c7588b949196f4a13d99e37e5eacfd.tar.gz crupest-1fa40aa140c7588b949196f4a13d99e37e5eacfd.tar.bz2 crupest-1fa40aa140c7588b949196f4a13d99e37e5eacfd.zip |
import(solutions): Add problem 35 .
-rw-r--r-- | works/solutions/cpp/35.cpp | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/works/solutions/cpp/35.cpp b/works/solutions/cpp/35.cpp new file mode 100644 index 0000000..7da26c4 --- /dev/null +++ b/works/solutions/cpp/35.cpp @@ -0,0 +1,36 @@ +#include <vector>
+
+using std::vector;
+
+class Solution
+{
+public:
+ int searchInsert(vector<int> &nums, int target)
+ {
+ if (nums.empty())
+ return 0;
+
+ int left_index = 0;
+ int right_index = nums.size();
+
+ while (left_index != right_index)
+ {
+ const int middle_index = (left_index + right_index) / 2;
+ const int middle_value = nums[middle_index];
+ if (target < middle_value)
+ {
+ right_index = middle_index;
+ }
+ else if (target > middle_value)
+ {
+ left_index = middle_index + 1;
+ }
+ else
+ {
+ return middle_index;
+ }
+ }
+
+ return left_index;
+ }
+};
|