Search Insert Position(二分查找)
2014-11-20 11:37
375 查看
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.二分查找时间复杂度O(logn)。
二分查找的基本思想是将n个元素分成大致相等的两部分,去a[n/2]与x做比较,如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则只要在数组a的右半部搜索x.
时间复杂度无非就是while循环的次数!
总共有n个元素,
渐渐跟下去就是n,n/2,n/4,....n/2^k,其中k就是循环的次数
由于你n/2^k取整后>=1
即令n/2^k=1
可得k=log2n,(是以2为底,n的对数)
所以时间复杂度为O(logn)
代码:
2.一般方法,复杂度O(n),先找出边界,然后就是相等和两数之间的情况。
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
1.二分查找时间复杂度O(logn)。
二分查找的基本思想是将n个元素分成大致相等的两部分,去a[n/2]与x做比较,如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则只要在数组a的右半部搜索x.
时间复杂度无非就是while循环的次数!
总共有n个元素,
渐渐跟下去就是n,n/2,n/4,....n/2^k,其中k就是循环的次数
由于你n/2^k取整后>=1
即令n/2^k=1
可得k=log2n,(是以2为底,n的对数)
所以时间复杂度为O(logn)
代码:
class Solution { public: int searchInsert(int A[], int n, int target) { int l=0; int r=n-1; int mid; while (l<=r) { mid=(l+r)/2; if(A[mid]>target) r=mid-1; else if(A[mid]<target) l=mid+1; else return mid; } if(l==r+1) return l; else if(r=-1) return 0; else if(l=n) return n; } };
2.一般方法,复杂度O(n),先找出边界,然后就是相等和两数之间的情况。
class Solution { public: int searchInsert(int A[], int n, int target) { if(target>A[n-1]) return n; if(target<A[0]) return 0; for(int i=0;i<n;++i) { if(A[i]==target) return i; if(i<(n-1)&&target>A[i]&&target<A[i+1]) return i+1; } } };
相关文章推荐
- 二分查找——Search Insert Position
- Leetcode 二分查找 Search Insert Position
- leetcode_35题——Search Insert Position(二分查找)
- [LeetCode]Search Insert Position (二分查找总结) Java Version
- LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)
- Leetcode 35 Search Insert Position 二分查找插入数字位置
- leetcode 35. Search Insert Position搜索插入位置(二分查找)
- Leetcode 35 Search Insert Position 二分查找(二分下标)
- leetcode——Search Insert Position 二分查找 binary search
- LeetCode @ Search Insert Position 二分查找
- LeetCode Search Insert Position (二分查找)
- LeetCode OJ 之 Search Insert Position (查找插入位置)
- LeetCode 35 Search Insert Position 二叉查找相关(一)
- LeetCode 35. Search Insert Position 二分查找
- [LeetCode] Serch Insert Position (总结二分查找) Java version
- LeetCode 35 Search Insert Position(查找插入位置)
- LeetCode | Search Insert Position(查找插入位置)
- Search Insert Position 查找位置
- [leetcode] 【查找】 35. Search Insert Position
- Search Insert Position:二分搜索