LeetCode – Search Insert Position
来源:互联网 发布:数据库管理系统功能 编辑:程序博客网 时间:2024/05/21 17:00
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
Solution 1
Naively, we can just iterate the array and compare target with ith and (i+1)th element. Time complexity is O(n)
public class Solution { public int searchInsert(int[] A, int target) { if(A==null) return 0; if(target <= A[0]) return 0; for(int i=0; i<A.length-1; i++){ if(target > A[i] && target <= A[i+1]){ return i+1; } } return A.length; }}
Solution 2
This also looks like a binary search problem. We should try to make the complexity to be O(nlogn).
public class Solution { public int searchInsert(int[] A, int target) { if(A==null||A.length==0) return 0; return searchInsert(A,target,0,A.length-1); } public int searchInsert(int[] A, int target, int start, int end){ int mid=(start+end)/2; if(target==A[mid]) return mid; else if(target<A[mid]) return start<mid?searchInsert(A,target,start,mid-1):start; else return end>mid?searchInsert(A,target,mid+1,end):(end+1); }}
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
- Oracle删除某个用户下的所有表数据,但不删除表结构
- 关于"No result defined for action com.ccxe.credit.action.ReportAction and result input"的错误
- 渐进符号(二)
- 配置自己的CocoaPods库
- 20个经典bootsrtap后台html网站模板推荐
- LeetCode – Search Insert Position
- Timeout expired. The timeout period elapsed prior to completion of the operation or the server is no
- 神奇的魔术方阵
- 提示microsoft incremental linker已停止工作解决方法
- CentOS6 rpm 安装Open vSwitch(OVS)报错
- 说说spring的自动装配
- Sqlite3支持的数据类型 日期函数 Sqlite3 函数
- Hdu 2082 找单词 母函数
- strcmp,strncmp,memcmp,strcat,strncat函数实现