LeetCode: Search Insert Position
来源:互联网 发布:淘宝帐号买家卖家分开 编辑:程序博客网 时间:2024/05/16 17:22
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(int A[], int n, int target) { if(n == 0)return 0;return binarySearch(0, n-1, target, A, n/2); }int binarySearch(int start, int end, int target, int A[], int preMid){if(start > end){if(A[preMid] < target){return preMid+1;}else{return preMid;}}int mid = (start + end) / 2;if(A[mid] == target)return mid;else if(A[mid] < target){return binarySearch(mid+1, end, target, A, mid);}else{return binarySearch(start, mid-1, target, A, mid);}}};
Round 2:
class Solution {public: int searchInsert(int A[], int n, int target) { int l = 0, r = n-1; while(l <= r) { int mid = (l+r)/2; if(A[mid] == target) return mid; else if(A[mid] < target) { if(mid == n-1) return n; if(A[mid+1] > target) return mid+1; l = mid+1; } else { if(mid == 0) return 0; if(A[mid-1] < target) return mid; r = mid-1; } } return 0; }};
0 0
- 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
- [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
- Leetcode: Search Insert Position
- LeetCode:Search Insert Position
- leetcode Search Insert Position
- LeetCode Search Insert Position
- 漫步IOS--MAC系统下的简单文件加密
- hdu oj 1061 Rightmost Digit (快速幂算法)
- STM32 学习九 通过USART实现printf重定向
- Jsoup解析HTML实例及文档方法详解
- Struts2返回JSON对象的方法总结
- LeetCode: Search Insert Position
- 冒泡排序和快速排序
- 同步(Synchronous)异步(Asynchronous) 阻塞(Blocking)和非阻塞(Non-blocking)的概念
- Java 序列化
- Blocks Programming Topics
- 那些让你犯迷糊的hibernate参数意思详解
- vb.net正则表达式快速入门(2)
- Unuser Variable‘ ’
- Android基础(一)