LeetCode -- Search Insert Position
2015-09-16 19:47
423 查看
Question:
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.
Analysis:
给出一个排好序的数组和一个目标值,如果数组中含有这个值则返回他的index;若不存在target,则返回应该插入额位置。
思路:
二分查找。定义两个指针,分情况讨论。注意边界情况。
Answer:
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
Analysis:
给出一个排好序的数组和一个目标值,如果数组中含有这个值则返回他的index;若不存在target,则返回应该插入额位置。
思路:
二分查找。定义两个指针,分情况讨论。注意边界情况。
Answer:
public class Solution { public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0) return -1; int i = 0, j = nums.length - 1; if(nums[i] > target) return 0; if(nums[j] < target) return j + 1; while(true) { int mid = i + (j - i) / 2; if(mid == i && nums[i] < target && nums[j] > target) { return j; } if(mid == i && nums[j] == target) { return j; } if(nums[mid] == target) return mid; if(nums[mid] > target) { j = mid; } if(nums[mid] < target) { i = mid; } } } }
相关文章推荐
- C++技术点积累(3)——对象初始化列表、运算符重载
- IOS rumen
- 加密一个密码
- Linux之间的文件共享
- asp.net 执行Response.Write后页面变形
- 使用正则限制input框只能输入数字/英文/中文等等
- HDU 5441 Travel (并查集)
- 纯代码实现QQ聊天界面---TableView使用详解
- iOS开发 -- WebSocket 通信(一)
- 在Linux下使用RAID(一):RAID的级别和概念介绍
- Material Design 开发利器:Android Design Support Library 介绍
- Android的开发环境的发展演变
- 软件工程的实践项目的自我目标
- 小猫统计——自定义数据汇总(二)
- 多重继承与虚继承
- 间隙锁(gap lock)个人实验(一)
- 如何不翻墙下载Android代码
- 对于9月16号股市的一点感想
- php将xml文件中的查询具体节点名字下的值
- 第八周第三天