博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode/LeetCode] Search Insert Position
阅读量:6966 次
发布时间:2019-06-27

本文共 718 字,大约阅读时间需要 2 分钟。

Problem

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.

Example

[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0

Challenge

O(log(n)) time

Note

标准二分法题目。

Solution

public class Solution {    public int searchInsert(int[] A, int target) {        int start = 0, end = A.length-1, mid;        if (A == null || A.length == 0) return 0;        while (start <= end) {            mid = (start+end)/2;            if (A[mid] == target) return mid;            else if (A[mid] < target) start = mid+1;            else end = mid-1;        }        return start;    }}

转载地址:http://qabsl.baihongyu.com/

你可能感兴趣的文章
python学习
查看>>
解决linux系统CentOS下调整home和根分区大小
查看>>
PHP问题 —— PHP Parse error: syntax error, unexpected
查看>>
JAVA基础知识之Set集合
查看>>
C++编译步骤
查看>>
数据库之Schema设计
查看>>
java 应用连接oracle 超级慢的解决方法
查看>>
tcp_tw_recycle和tcp_timestamps导致connect失败问题
查看>>
mybatis中的#和$的区别
查看>>
Linux中的echo简介(自我总结)(44)
查看>>
Selenium Firefox启动提示导入收藏夹
查看>>
springboot oauth2 fetch 关于跨域请求的问题
查看>>
PostgreSQL调研
查看>>
软件熵:软件开发中推倒重来的过程就是软件熵不断增加的过程
查看>>
如何安装Google浏览器插件
查看>>
Spring Cloud Config 集中式配置
查看>>
java生成验证码
查看>>
Android学习——基础组件
查看>>
Java Socket通信编程
查看>>
getopt函数—分析命令行参数
查看>>