File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+
3+ Given a sorted array and a target value, return the index if the target is found.
4+ If not, return the index where it would be if it were inserted in order.
5+
6+ You may assume no duplicates in the array.
7+
8+ Example 1:
9+
10+ Input: [1,3,5,6], 5
11+ Output: 2
12+
13+ */
14+
15+ // solution
16+
17+ class Solution {
18+ public:
19+ int searchInsert (vector<int >& nums, int target) {
20+ int low = 0 ,high = nums.size ()-1 ;
21+ int mid;
22+ if (target <= nums[0 ])
23+ {
24+ return 0 ;
25+ }
26+ else if (target > nums[nums.size ()-1 ])
27+ {
28+ return nums.size ();
29+ }
30+ while (low <= high)
31+ {
32+ mid = low + (high - low)/2 ;
33+ if (nums[mid] == target)
34+ return mid;
35+ if (nums[mid] < target)
36+ low = mid + 1 ;
37+ else
38+ high = mid - 1 ;
39+ }
40+
41+ if (mid!=0 && nums[mid-1 ] < target && nums[mid] >= target){
42+ return mid;
43+ }
44+ else
45+ {
46+ return mid+1 ;
47+ }
48+
49+ }
50+ };
You can’t perform that action at this time.
0 commit comments