leetcode:Search Insert Position 【Java 】
2016-03-03 13:21
393 查看
一、问题描述
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.
二、问题分析
借助二分查找算法实现查找插入位置。
三、算法代码
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[] nums, int target) { int start = 0; int end = nums.length - 1; int middle = 0; while(start <= end){ middle = (start + end)/2; if(nums[middle] == target){ return middle; } if(nums[middle] > target){ end = middle - 1; }else{ start = middle + 1; } }//end while if(nums[middle] > target){ return middle;//重点 }else{ return middle + 1; } } }
相关文章推荐
- spring mvc的DefaultServlet的作用
- Java基础日记
- 安卓开发入门之eclipse配置java和adb环境
- java为什么要设置环境变量
- java内部类
- 【Java难点】 String类与Stri…
- 【孙鑫Java教程笔记】第二课 Java …
- 【孙鑫Java教程笔记】第一课:Java…
- 【Java 易混点】 关于eq…
- 【Java 知识重点】JRE与JDK区别
- Eclipse常用的优秀插件在线更新地址,包括MyEclipse10.0
- 【Java 知识重难点】Java语言…
- 【Java 重难点知识】String s=new …
- 【慕课笔记】5-1 JAVA中的进制
- servlet接收web上传文件
- [转]java.lang.OutOfMemoryError: PermGen space及其解决方法
- 如何取消eclipse对文档注释和多行注释的格式化
- hadoop之mapreduse 在Eclipse下的调试环境篇
- java.lang.IllegalArgumentException: System memory 468189184 must be at least 4.718592E8
- struts2接收参数的三种方式