Search Insert Position
来源:互联网 发布:苹果手机价格评估软件 编辑:程序博客网 时间:2024/05/01 18:19
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
思路:binary search,注意头和尾的处理。
public class Solution { public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0) return -1; int start = 0; int end = nums.length-1; while(start<=end){ int mid = start +(end-start)/2; if(nums[mid] == target){ return mid; } else { if(nums[mid] < target){ if(mid+1 == nums.length){ return nums.length; } else if(target < nums[mid+1]) { return mid+1; }else { start = mid+1; } } else { // target < nums[mid]; if(mid-1 == -1){ return 0; } else if(nums[mid-1]< target){ return mid; } else { end = mid-1; } } } } return -1; } }
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
- Letter Combinations of a Phone Number - LeetCode
- [MySQL Delay]生产环节主从延迟的问题解决过程记录: sync_binlog=0
- 关于 hadoop-2.2 配置中的 yarn.nodemanager.aux-services 项
- SAP Cloud offering (网络搜集)
- Binary Tree Inorder Traversal - LeetCode
- Search Insert Position
- Android Studio java.lang.RuntimeException: Unable to start activity ComponentInfo
- 用C/C++设计Lu结构、字典、类等高级数据类型
- C/C++使用MLu简化Lu脚本系统的使用
- hdu2222_ac自动机模版题
- 查看 rpm包依赖性
- 从“史记2013”看百度百科的新媒体态度
- linux的RPM查询命令
- win32 dll简单例子