-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path35.cpp
More file actions
28 lines (27 loc) · 780 Bytes
/
35.cpp
File metadata and controls
28 lines (27 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Author: btjanaka (Bryon Tjanaka)
// Problem: (LeetCode) 35
// Title: Search Insert Position
// Link: https://leetcode.com/problems/search-insert-position
// Idea: Use binary search to find the location, since the array is sorted.
// Difficulty: easy
// Tags: binary-search
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.size() == 0) return 0;
if (target < nums[0]) return 0;
if (target > nums.back()) return nums.size();
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
};