60. 搜索插入位置
来源:互联网 发布:快手知希大人真名 编辑:程序博客网 时间:2024/06/05 04:03
题目描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[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 { /* * @param A: an integer sorted array * @param target: an integer to be inserted * @return: An integer */ public int searchInsert(int[] A, int target) { // write your code here if (A.length==0){ return 0; } int start = 0; int end = A.length-1; int mid; while(start<end){ mid = start+ (end-start)/2; if (A[mid]>target){ end=mid-1; } if (A[mid]<target){ start = mid+1; } if (A[mid]==target){ end=mid; } } if (A[start]>=target){ return start; } else return start+1; }}
阅读全文
0 0
- 60. 搜索插入位置
- lintcode python 容易 60.搜索插入位置
- 题目:搜索插入位置
- LintCode : 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode ----搜索插入位置
- LintCode : 插入搜索位置
- 搜索插入位置
- Lintcode 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode:搜索插入位置
- Lintcode搜索插入位置
- lintCode 搜索插入位置
- LintCode_060_搜索插入位置
- SEO好不好做全看竞争对手!5招教你如何甩开对手几条街?
- CSS日常随笔:BFC块级格式上下文
- 1063. 计算谱半径(20) PAT乙级真题
- linux下mount命令实现文件跨服务器的挂载
- 20171207-学习日记
- 60. 搜索插入位置
- 列举一些MongoEngine的filter方法
- c语言经典算法——查找一个整数数组中第二大数
- android开发如何获取电话号码的归属地信息
- 关于阿里矢量图iconfont的应用
- 总结 2017-12-07
- canvas调用webgl绘制图形图像
- C++标准库学习笔记-5-(Container)
- C到CPP的注释转换