本文主要是介绍Leetcode81: Search 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.
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
两种方法,一种直接遍历,一种二分查找
class Solution {
public:int searchInsert(vector<int>& nums, int target) {int size = nums.size();if(size == 0)return 0;int i;for(i = 0; i < size; i++){if(target <= nums[i])return i;}return i;}
};
class Solution {
public:int searchInsert(vector<int>& nums, int target) {int size = nums.size();int low = 0, high = size-1;while(low <= high) {int mid = (low+high)>>1;if(nums[mid] == target) return mid;else if(nums[mid] > target) high = mid-1;elselow = mid+1;}if(high < 0) return 0;if(low >= size) return size;return low;}
};
这篇关于Leetcode81: Search Insert Position的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!