leetcode:Search Insert Position
来源:互联网 发布:linux sysctl 优化 编辑:程序博客网 时间:2024/04/30 11:33
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 n=nums.length; if(n==0) return 0; for(int i=0;i<n;i++) { if(nums[i]>=target) return i; } return n; }}
二分法
二分法总是搞不清该返回 low 还是 high
若是真的要解释话. 最终 low == high, 这个时候, Mid = low = high. 假如 A[mid]>target, 那么插入位置就是 mid 处, 返回 low, OK. 假如 A[mid] < target, 那么 low = mid+1, 仍然返回 low
public class Solution { public int searchInsert(int[] nums, int target) { int n=nums.length; int i=0,j=n-1,k=0; if(n==0) return 0; if(target>nums[n-1]) return n; if(target<nums[0]) return 0; while(i<=j) { k=(i+j)/2; if(nums[k]<target) i=k+1; else if(nums[k]>target) j=k-1; else return k; } return i; }}
0 0
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode-Search Insert Position
- LeetCode - Search Insert Position
- LeetCode | Search Insert Position
- Leetcode: Search Insert Position
- 【LeetCode】Search Insert Position
- Leetcode Search Insert Position
- Leetcode: Search Insert Position
- LeetCode:Search Insert Position
- leetcode Search Insert Position
- LeetCode Search Insert Position
- 用友通服务无法启动-解决汇总【随时更新】
- 演讲讲稿--创新与落实
- sql2005数据库连接不上,错误:233/错误:18452
- Centos 6.4 python 2.6 升级到 2.7
- 二维数组中查找一个数是否存在
- leetcode:Search Insert Position
- FC经典游戏通关视频
- wmp不能播放swf文件解决办法
- Android ViewPager禁止滑动
- 大数据工具/框架
- ConfigurationException异常
- 【转】WIN7 IIS安装
- 【leetcode】25. Reverse Nodes in k-Group
- SQL2000/2005版本号