[LeetCode] Search Insert Position 解题报告
来源:互联网 发布:淘宝网羽绒服女装 编辑:程序博客网 时间:2024/06/05 15:18
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» Solve this problem
[解题思路]
跟经典的二分查找相比,只是多了一个条件:
if(mid>left && A[mid]>target && A[mid-1]<target)
[Code]
1: int searchInsert(int A[], int n, int target) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int l=0, r=n-1;
5: while(l<=r)
6: {
7: int mid = (l+r)/2;
8: if(A[mid] == target) return mid;
9: if(mid>l && A[mid]>target && A[mid-1]<target ) return mid;
10: if(A[mid] > target)
11: {
12: r= mid-1;
13: }
14: else
15: {
16: l=mid+1;
17: }
18: }
19: return l;
20: }
0 0
- LeetCode解题报告--Search Insert Position
- [leetcode] 35. Search Insert Position 解题报告
- [LeetCode] Search Insert Position 解题报告
- Leetcode解题报告:Search Insert Position
- [Leetcode] 35. Search Insert Position 解题报告
- 【LeetCode】Search Insert Position 解题报告
- [leetcode]解题报告35. Search Insert Position
- 【LeetCode】35.Search Insert Position解题报告
- Leetcode Search Insert Position解题报告
- Leetcode #35. Search Insert Position 搜寻插入位置 解题报告
- leetcode解题方案--035--Search Insert Position
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- 使用flume thrift source的一点心得
- 虚拟机性能监控与故障处理工具
- [LeetCode] Search in Rotated Sorted Array 解题报告
- [LeetCode] Search in Rotated Sorted Array II 解题报告
- git管理相关命令
- [LeetCode] Search Insert Position 解题报告
- [LeetCode] Set Matrix Zeroes 解题报告
- [LeetCode] Simplify Path 解题报告
- Mac 装双系统
- [LeetCode] Sort Colors 解题报告
- Unity Shader中顶点坐标的大小似乎会受到Draw Call合批的影响
- java +号字符串拼接原理解释以及StringBulider比较
- [LeetCode] Spiral Matrix 解题报告
- [LeetCode] Sqrt(x) 解题报告