35. Search Insert Position [LeetCode]

版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/80998697

35Search Insert Position

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 4:

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

//暴力遍历
class Solution_35_1 {
public:
	int searchInsert(vector<int>& nums, int target) {	
		if (target>nums[nums.size() - 1])return nums.size();
		if (target<nums[0])return 0;

		int result = 0;

		for (int i = 0; i != nums.size(); ++i) 
			if (!(nums[i]<target)){
				result = i;
				break;
			}
		return result;
	}
};

//重新实现lower_bound  O(logN)
class Solution_35_2 {
public:
	int searchInsert(vector<int>&nums, int target) {
		return distance(nums.begin(), _lower_bound(nums.begin(), nums.end(), target));
	}
private:
	template<typename ForwardIterator,typename T>
	ForwardIterator _lower_bound(ForwardIterator first, ForwardIterator last, T val) {
		while (first != last) {
			auto mid = next(first, distance(first, last) / 2);
			if (val > *mid)first = ++mid;
			else last = mid;
		}
		return first;
	}
};



猜你喜欢

转载自blog.csdn.net/MC_007/article/details/80998697