35. Search Insert Position
2017-09-19 09:23
323 查看
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
二分查找
C++(6ms):
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 int left = 0 ; 5 int right = nums.size()-1 ; 6 while(left <= right){ 7 int mid = left + (right - left)/2 ; 8 if (target == nums[mid]) 9 return mid ; 10 else if(target > nums[mid]) 11 left = mid + 1; 12 else 13 right = mid - 1; 14 } 15 return left ; 16 } 17 };
相关文章推荐
- 35. Search Insert Position
- LeetCode 35 Search Insert Position
- LeetCode-35-Search Insert Position(二分法)-Medium
- [Leetcode]_35 Search Insert Position
- 2018.04.02 leeycode 打卡 #35 . Search Insert Position
- 35. Search Insert Position
- FTPrep, 35 Search Insert Position
- [35]Search Insert Position
- leetcode - 35.Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35 Search Insert Position
- 35 Search Insert Position
- 35. Search Insert Position(unsolved)
- 35. Search Insert Position
- 35. Search Insert Position(第九周)
- 【LeetCode】35. Search Insert Position (2 solutions)
- LeetCode 35 Search Insert Position
- [leedcode 35] Search Insert Position
- 2018.04.02 leeycode 打卡 #35 . Search Insert Position