60.Search Insert Position-搜索插入位置(容易题)
来源:互联网 发布:java实现短信发送 编辑:程序博客网 时间:2024/05/20 04:31
搜索插入位置
题目
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
题解
1.简单遍历即可。
public class Solution { /** * param A : an integer sorted array * param target : an integer to be inserted * return : an integer */ public int searchInsert(int[] A, int target) { for (int i=0;i<A.length;i++) { if (A[i] >= target) { return i; } } return A.length; }}
2.排序数组使用二分法效率更好。
public class Solution { /** * param A : an integer sorted array * param target : an integer to be inserted * return : an integer */ public int searchInsert(int[] A, int target) { int low = 0; int high = A.length-1; while (low <= high) { int mid = low + (high - low) / 2; if (target < A[mid]) { if (mid == 0 || target > A[mid-1]) { return mid; } high = mid - 1; } else if (target > A[mid]) { if (mid == A.length - 1) { return ++mid; } low = mid + 1; } else { return mid; } } return A.length; }}
Last Update 2016.8.28
0 0
- 60.Search Insert Position-搜索插入位置(容易题)
- 【LintCode】Search Insert Position 搜索插入位置
- 搜索插入位置:Search Insert Position
- Search Insert Position 插入位置
- 【LeetCode】Search Insert Position搜索插入位置[数组、二分法]
- leetcode 35. Search Insert Position搜索插入位置(二分查找)
- 【LeetCode-面试算法经典-Java实现】【035-Search Insert Position(搜索插入位置)】
- 【LeetCode】- Search Insert Position(查找插入的位置)
- LeetCode | Search Insert Position(查找插入位置)
- LeetCode OJ 之 Search Insert Position (查找插入位置)
- LeetCode---35. Search Insert Position(查找插入位置)
- LeetCode Search Insert Position查找插入位置
- Search Insert Position 查找插入的位置
- Search Insert Position 寻找插入的位置
- 35. Search Insert Position 查找插入位置
- LeetCode 35 Search Insert Position(搜索并插入)
- LeetCode 35. Search Insert Position(搜索插入点)
- leetCode 35.Search Insert Position (搜索插入位置) 解题思路和方法
- 【用Cocos Creator给暗恋的女生写一个游戏(5)】——(Run Game)场景搭建
- 图解 VS 2015 线程调试窗口解析
- LeetCode389. Find the Difference简单
- VirtualBox - 自动调整屏幕大小,显示分辨率
- FBO中多重采样抗锯齿(MSAA:MultiSampling Anti-Aliasing)
- 60.Search Insert Position-搜索插入位置(容易题)
- android Sugar ORM
- 一图看懂回调函数的使用与妙处
- NDK开发之Android Studio生成.h头文件的方法
- UICollectionView使用(WWDC session学习笔记)
- Hibernate 注解映射
- css 引入方式,选择器,选择器的优先级
- 苹果开发者账号相关系列
- git 与svn的区别