summaryrefslogtreecommitdiff
path: root/cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-05-15 17:01:47 +0800
committercrupest <crupest@outlook.com>2020-05-15 17:01:47 +0800
commit65260343ad6b769c9a57eac206ddd77a57f81116 (patch)
tree1c959f669455ed8fa4dc23eedac26c26797cea67 /cpp
parenta5a864572f952072ab1d36b7133c9737bf6e1586 (diff)
downloadsolutions-65260343ad6b769c9a57eac206ddd77a57f81116.tar.gz
solutions-65260343ad6b769c9a57eac206ddd77a57f81116.tar.bz2
solutions-65260343ad6b769c9a57eac206ddd77a57f81116.zip
Add problem 35 .
Diffstat (limited to 'cpp')
-rw-r--r--cpp/35.cpp36
1 files changed, 36 insertions, 0 deletions
diff --git a/cpp/35.cpp b/cpp/35.cpp
new file mode 100644
index 0000000..7da26c4
--- /dev/null
+++ b/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;
+ }
+};