Search Insert Position
来源:互联网 发布:最短路径算法有 编辑:程序博客网 时间:2024/04/28 14:47
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
答案
- public class Solution {
- public int searchInsert(int[] A,int target) {
- if(target<=A[0])
- {
- return 0;
- }
- if(target>A[A.length-1])
- {
- return A.length;
- }
- int start=0;
- int end=A.length-1;
- while(start<=end)
- {
- int middle=start+(end-start)/2;
- if(A[middle]==target)
- {
- return middle;
- }
- else
- {
- if(target>A[middle])
- {
- if(target<=A[middle+1])
- {
- return middle+1;
- }
- start=middle+1;
- }
- else
- {
- if(target>A[middle-1])
- {
- return middle;
- }
- end=middle-1;
- }
- }
- }
- return 0;
- }
- }
0 0
- LeetCode: Search Insert Position
- Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode34:Search Insert Position
- Search Insert Position
- [35]Search Insert Position
- Search Insert Position
- Search Insert Position
- [LeetCode]Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- Search Insert Position
- Search Insert Position
- NYOJ-最大值和最小值
- 使用接插件需要注意的问题
- DSP6000的上电及供电
- 嵌入式linux下自动定时检测硬盘空间并删除旧文件脚本
- DSP6000的几个简单优化技巧
- Search Insert Position
- 数字信号处理的学习资源
- 北大"小师妹"走红 网友赞许预备役校花
- NetGear stora 重置成功后,个人文件夹丢失的找回办法
- 实拍草根模特的一天 饮食不规律常被性骚扰(图)
- 孙杨国歌门事件掀中日骂战 日本国歌有多难听你知道吗?
- 锋菲被曝复合内幕 谢霆锋为“复合”精心部署
- 王祖贤素颜现身疑整形 明星整容前后对比照惨不忍睹
- 云编程那些事4 - 不造巴比伦塔