From 630820851dabca5a19e4a0dc6fd4d547d0927de1 Mon Sep 17 00:00:00 2001 From: Swapnilkumar Dwivedi <122719184+swappy-2003@users.noreply.github.com> Date: Tue, 16 Jan 2024 23:00:39 +0530 Subject: [PATCH] Update binary-search.cpp This is an updated code as Previous code doesnt handle all cases on leetcode --- Leetcode/binary-search.cpp | 55 +++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/Leetcode/binary-search.cpp b/Leetcode/binary-search.cpp index dfd6c14..311cb97 100644 --- a/Leetcode/binary-search.cpp +++ b/Leetcode/binary-search.cpp @@ -1,20 +1,43 @@ -// https://leetcode.com/problems/binary-search/submissions/ +// // https://leetcode.com/problems/binary-search/submissions/ +// class Solution { +// public: +// int search(vector& nums, int target) { +// int left = 0; +// int right = nums.size()-1; + +// while (left <= right) +// { +// int middle = left + (right-left)/2; +// if(nums[middle] == target) +// return middle; +// if(nums[middle] > target) +// right--; +// else +// left++; +// } +// return -1; +// } +// }; + +// updated code as perivous code doesnt handle all the test cases on leetcode class Solution { public: - int search(vector& nums, int target) { - int left = 0; - int right = nums.size()-1; - - while (left <= right) - { - int middle = left + (right-left)/2; - if(nums[middle] == target) - return middle; - if(nums[middle] > target) - right--; - else - left++; + int searchInsert(std::vector& nums, int target) { + int start = 0; + int end = nums.size(); + + while (start < end) { + int mid = start + (end - start) / 2; + + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < target) { + start = mid + 1; + } else { + end = mid; + } } - return -1; + + return start; // If the target is not found, return the insertion position } -}; \ No newline at end of file +};