Search Insert Position
来源:互联网 发布:linux 启动脚本 编辑:程序博客网 时间:2024/06/03 02:25
问题描述:一个排好序的int数组,给定一个值target。如果数组中有target,返回target的下标,如果target不再数组里,返回其插入进数组的下标。
解决:对于排好序的数组,使用二分法查找。
/* * 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 SearchInsert { public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0) { return -1; } int begin = 0; int end = nums.length-1; while(begin <= end) { int mid = (begin + end)/2; if(target == nums[mid]) { return mid; } else if(target < nums[mid]){ end = mid-1; } else { begin = mid+1; } } return begin; }}
阅读全文
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
- 原生JAVA解析json
- 51nod 1133不重合线段
- 机器学习——简单线性回归(下)
- DFS:POJ3620-Avoid The Lakes(求最基本的联通块)
- 史上最牛的员工激励
- Search Insert Position
- wget命令参数用法总结
- 2017乌鲁木齐网络赛D题 区间dp
- appium并发测试
- jquery操作复选框的总结
- Selenium with Python中文翻译(八)
- js的call方法和apply方法
- POJ 3259Wormholes
- nohup command 2>&1 &的解释