博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]35.Search Insert Position
阅读量:4598 次
发布时间:2019-06-09

本文共 1132 字,大约阅读时间需要 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.

Example 1:

Input: [1,3,5,6], 5

Output: 2
Example 2:

Input: [1,3,5,6], 2

Output: 1
Example 3:

Input: [1,3,5,6], 7

Output: 4
Example 4:

Input: [1,3,5,6], 0

Output: 0

解法一

思路

直接遍历一次数组即可,如果目标值小于等于当前位置的值,直接返回下标即可,当一遍循环结束的时候,还没有返回,说明目标值比数组中的所有值都大,此时直接返回数组长度即可。时间复杂度为O(n)。

代码

class Solution {    public int searchInsert(int[] nums, int target) {        for(int i = 0; i < nums.length; i++) {            if(target <= nums[i])                return i;        }        return nums.length;    }}

解法二

思路

用二分法的思路,时间复杂度为O(log2n)。

代码

class Solution {    public int searchInsert(int[] nums, int target) {        int low = 0;        int high = nums.length - 1;        while(low <= high) {            int mid = (low+high)/2;            if(target == nums[mid]) return mid;            else if (target < nums[mid]) high = mid - 1;            else low = mid + 1;               }        return low;    }}

转载于:https://www.cnblogs.com/shinjia/p/9727900.html

你可能感兴趣的文章
最简单的三层实例【插入据
查看>>
设计模式学习笔记——Prototype原型模式
查看>>
pom.xml里有红叉报错的解决办法
查看>>
Perl last和next的用法区别
查看>>
Selenium 管理 Cookies
查看>>
exceptionfunction[LeetCode]Permutations
查看>>
Linux(2)_常用命令2
查看>>
自定义分页
查看>>
[转]DELPHI——调试(1)
查看>>
JS秒数转成分秒时间格式
查看>>
xp_cmdshell 命令的开启与关闭,和状态查询
查看>>
Linux sudoers
查看>>
MySQL详解(18)-----------分页方法总结
查看>>
bzoj 4595 激光发生器
查看>>
multi cookie & read bug
查看>>
js时间转换
查看>>
(转载) Android Studio你不知道的调试技巧
查看>>
POJ2231 Moo Volume 递推 C语言
查看>>
struts2类型转换的具体流程
查看>>
Hdu 1203 I NEED A OFFER!
查看>>