letecode [35] - 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.
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
题目大意:
在给定排序数组中,查找某个数。若找到,则返回该数下标;否则,返回该数应被插入位置的下标。
理 解 :
使用二分法进行查找具有较高的效率。
这里,我的代码可以实现该元素的插入。在二分法查找的基础上实现插入。
代 码 C++:
class Solution { public: int searchInsert(vector<int>& nums, int target) { int n = nums.size(); if(n==0){ nums[0] = target; return 0; } if(n==1){ if(nums[0]==target) return 0; else if(nums[0]>target){ nums.push_back(target); nums[1] = nums[0]; nums[0] = target; return 0; }else{ nums.push_back(target); return 1; } } int left=0,right=n-1,mid,i; while(left<right){ mid = (left+right)/2; if(nums[mid]>target){ right = mid-1; }else if(nums[mid]==target){ return mid; }else{ left = mid + 1; } } mid = (left+right)/2; if(nums[mid]>target){ nums.push_back(target); for(i=n;i>mid;--i){ nums[i] = nums[i-1]; } nums[mid] = target; return mid; }else if(nums[mid]<target){ nums.push_back(target); for(i=n;i>mid+1;--i){ nums[i] = nums[i-1]; } nums[mid+1] = target; return mid+1; }else{ return mid; } } };
运行结果:
执行用时 : 8 ms 内存消耗 : 9 MB