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

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

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], 5Output: 2Example 2:Input: [1,3,5,6], 2Output: 1Example 3:Input: [1,3,5,6], 7Output: 4Example 4:Input: [1,3,5,6], 0Output: 0

难度:easy

题目:

给定一个排序数组和目标值,如果目标值存在则返回目标值所在的位置,否则返回目标值所在的插入位置。

思路:二叉搜索树。

Runtime: 3 ms, faster than 59.63% of Java online submissions for Search Insert Position.

Memory Usage: 27.1 MB, less than 77.12% of Java online submissions for Search Insert Position.

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

Runtime: 3 ms, faster than 59.63% of Java online submissions for Search Insert Position.

Memory Usage: 28.7 MB, less than 12.43% of Java online submissions for Search Insert Position.

class Solution {    public int searchInsert(int[] nums, int target) {        return binarySearch(nums, 0, nums.length - 1, target);    }        private int binarySearch(int[] nums, int left, int right, int target) {        if (left > right) {            return left;        }        int mid = left + (right - left) / 2;        if (target == nums[mid]) {            return mid;        }                if (target > nums[mid]) {            return binarySearch(nums, mid + 1, right, target);        } else {            return binarySearch(nums, left, mid - 1, target);        }    }}

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

你可能感兴趣的文章
Flume(一)Flume原理解析
查看>>
python爬虫之基本知识
查看>>
Internet spirit
查看>>
Day004
查看>>
API之子窗口创建 (转)
查看>>
【iOS-iap防护】验证用户付费收据!拒绝iap Cracker!!让iphone越狱用户无从下手!!!...
查看>>
Jquery 遍历 Table;遍历CheckBox ;遍历Select;全选/全不选
查看>>
day14 内置函数二
查看>>
Sequelize-nodejs-2-basic usage
查看>>
XVI Open Cup named after E.V. Pankratiev. GP of Ekaterinburg.
查看>>
iOS-中app启动闪退的原因
查看>>
iOS--高级技术
查看>>
入门·开始使用机器学习
查看>>
【备忘】oc 调用 swift
查看>>
screen命令总结
查看>>
struct内存对齐
查看>>
套接字基础
查看>>
【转】配置Editplus调试PHP程序入门教程
查看>>
iphone-common-codes-ccteam源代码 CCKeyboard.h
查看>>
Javascript中的原型prototype
查看>>