leetcode - 35. Search Insert Position - Easy

descrition

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.


Example 1:
Input: [1,3,5,6], 5
Output: 2

Example 2:
Input: [1,3,5,6], 2
Output: 1

Example 3:
Input: [1,3,5,6], 7
Output: 4

Example 1:
Input: [1,3,5,6], 0
Output: 0

解析

二分查找的实现。

code


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public:
	int searchInsert(vector<int>& nums, int target){
		int ileft = 0, iright = nums.size() - 1;
		while(ileft <= iright){
			int imid = ileft + (iright - ileft) / 2;
			if(nums[imid] == target)
				return imid;
			else if (nums[imid] < target){
				ileft = imid + 1;
			}else{
				// nums[imid] > target
				iright = imid - 1;
			}
		}

		return ileft;
	}
};

int main()
{
	return 0;
}

相关文章:

  • 2021-09-21
  • 2021-09-29
  • 2021-11-08
  • 2022-03-06
  • 2021-11-27
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-01-03
  • 2021-07-12
  • 2021-08-12
  • 2021-08-09
  • 2021-07-12
  • 2021-09-27
  • 2021-09-07
相关资源
相似解决方案