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

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

题目:

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

思路:

二分查找

package array;public class SearchInsertPosition {    public int searchInsert(int[] nums, int target) {        int n;        if (nums == null || (n = nums.length) == 0) return 0;        int start = 0;        int end = n - 1;        int index = -1;        while (start <= end) {            int mid = (end - start) / 2 + start;            if (nums[mid] == target) {                index = mid;                break;            } else if (nums[mid] < target) {                start = mid + 1;            } else {                end = mid - 1;            }        }                if (index == -1)            index = end + 1;                return index;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        SearchInsertPosition s = new SearchInsertPosition();        int[] nums = { 1, 3, 5 };        System.out.println(s.searchInsert(nums, 7));    }}

 

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

你可能感兴趣的文章
greenplum分区表查看所占空间大小[转]
查看>>
c# ffmpeg wrapper
查看>>
git工作流介绍--结合sourcetree
查看>>
新一代UEFI BIOS UEFI基础知识介绍 (1)
查看>>
阻止OSPF路由
查看>>
python实现的json数据以HTTP GET,POST,PUT,DELETE方式页面请求
查看>>
ubuntu系统下修改mysql数据目录
查看>>
Apache URL Rwrite
查看>>
kubernetes1.8.5集群安装(带证书)
查看>>
ttlsa教程系列之mongodb——(三)mongodb的增删查改
查看>>
shell脚本中实现自动判断用户有无密码
查看>>
自动生成sql代码
查看>>
Nginx打开目录浏览功能(autoindex)
查看>>
我的友情链接
查看>>
RHEL5.4下如何创建yum源,如何使用yum命令
查看>>
正则表达式的使用
查看>>
用JDBC写的对oracle数据库增删改查的小程序
查看>>
关于Nginx的一些优化
查看>>
J2EE系统异常的处理准则
查看>>
TCP三次握手连接及seq和ack号的正确理解
查看>>