lintcode-easy-Search Insert Position
2016-03-07 06:54
267 查看
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.
You may assume NO duplicates in the array.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
public class Solution { /** * param A : an integer sorted array * param target : an integer to be inserted * return : an integer */ public int searchInsert(int[] A, int target) { // write your code here if(A == null || A.length == 0) return 0; int left = 0; int right = A.length - 1; if(target <= A[left]) return 0; if(target > A[right]) return A.length; while(left < right - 1){ int mid = left + (right - left) / 2; if(A[mid] == target) return mid; else if(A[mid] < target) left = mid; else right = mid - 1; } if(A[left] < target) return left + 1; return left; } }
相关文章推荐
- 关于Xcode上的Other linker flags
- CSS name
- Linux 文件权限管理
- 并发编程之线程安全性
- android中SO文件动态调试
- Xposed如何实现类中函数的调用
- C++ 静态数组过大,栈溢出
- 我与小娜(27):AlphaGo围棋手的技术奥秘
- lintcode-easy-Rotate String
- form v
- nike 2015 bccz icdu mtdf
- 最新VisualStudio 2015调试技巧
- 1.经典入门hello world
- lintcode-easy-Reverse Words in a String
- 162. Find Peak Element
- 正则
- 332. Reconstruct Itinerary
- Leetcode:195. Tenth Line以及管道命令pipeline
- 前端开发之Chrome插件
- 磨难持久而又痛苦,所以才能成长