Leetcode-search-insert-position
2016-06-27 17:45
435 查看
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
拿到题目,映入脑海中就是而非查找,找到就return位置,找不到就从头到尾找到合适插入的位置,于是乎,这是我的代码:
但是,发现找合适插入位置的方法不对,应该是最后停下来的start位置就是我们要return的位置。
public static int searchInsert(int[] A, int target) {
int start = 0;
int end = A.length-1;
while(start <= end){
int mid = (start+end) / 2;
if(A[mid] == target){
return mid;
}else if(A[mid] > target){
end = mid-1;
}else{
start = mid+1;
}
}
return start;
}
但是当我点开别人这样的代码的时候
public class Solution {
public int searchInsert(int[] A, int target) {
for(int i=0;i<A.length;i++)
{
if(target<=A[i])
return i;
}
return A.length;
}
}
我觉得我自己就是智障! 因为原数组是排好序的,找到大于等于target的位置就是我们想要return的位置呀!哎,看到这个代码,我很尴尬。
题目描述
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
拿到题目,映入脑海中就是而非查找,找到就return位置,找不到就从头到尾找到合适插入的位置,于是乎,这是我的代码:
public class Solution { public int searchInsert(int[] A, int target) { int start = 0; int end = A.length-1; boolean isFound = false; while(start <= end){ int mid = (start+end) / 2; if(A[mid] == target){ isFound = true; return mid; }else if(A[mid] > target){ end = mid-1; }else{ start = mid+1; } } if(!isFound){ if(target<A[0]){ return 0; }else if(target > A[A.length-1]){ return A.length; }else{ for(int i=1; i<A.length; i++){ if(A[i-1] < target && A[i] > target){ return i; } } } } return 0; } }
但是,发现找合适插入位置的方法不对,应该是最后停下来的start位置就是我们要return的位置。
public static int searchInsert(int[] A, int target) {
int start = 0;
int end = A.length-1;
while(start <= end){
int mid = (start+end) / 2;
if(A[mid] == target){
return mid;
}else if(A[mid] > target){
end = mid-1;
}else{
start = mid+1;
}
}
return start;
}
但是当我点开别人这样的代码的时候
public class Solution {
public int searchInsert(int[] A, int target) {
for(int i=0;i<A.length;i++)
{
if(target<=A[i])
return i;
}
return A.length;
}
}
我觉得我自己就是智障! 因为原数组是排好序的,找到大于等于target的位置就是我们想要return的位置呀!哎,看到这个代码,我很尴尬。
相关文章推荐
- 异常值的观测
- 自定义选择器(同时支持单滚轮和双滚轮联动选择器)
- 第四专题 Problem J
- MySQL出现SQL Error (2013)连接错误的解决方法
- amq笔记:记一个关于PooledConnectionFactory的问题
- iOS 归档解档
- 【开源】.Net 动态脚本引擎NScript
- 模拟器键盘Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad
- javaweb学习总结(十一)——使用Cookie进行会话管理
- text()/html()/val()的区别
- 几款实用android studio插件
- Block在界面之间的基本使用(传值操作, 方法嵌套)
- Linux创建、删除 文件和文件夹
- MySQL行级锁、表级锁、页级锁详细介绍
- 剑指offer题解 两个链表的第一个公共结点
- 时间序列数据库的秘密(3)——加载和分布式计算
- ubuntu英文系统下怎样安装中文输入法
- Java移位运算之算术右移位
- 数据库范式
- IOS手势识别,捏合,旋转,轻扫等