算法系列——Search Insert Position
来源:互联网 发布:淘宝商品质量问题定义 编辑:程序博客网 时间:2024/06/05 08:23
题目描述
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
解题思路
这是最典型的二分搜索法。while循环的条件是low<=high,如果target和mid指向的值相等,则返回mid,否则根据情况low = mid + 1或者high = mid - 1。这样的好处是,如果找不到该数,high是比该数小的那个数的下标,而low是比该数大的那个数的下标。这题中,我们返回low就行了
程序实现
public class Solution { public int searchInsert(int[] nums, int target) { if(nums==null||nums.length==0) return 0; int len=nums.length; int low=0,mid=0,high=len-1; while(low<=high){ mid=(low+high)/2; if(nums[mid]==target) return mid; if(nums[mid]>target) high=mid-1; else low=mid+1; } return low; }}
阅读全文
0 0
- 算法系列——Search Insert Position
- Search Insert Position算法
- LeetCode—Search Insert Position
- LeetCode算法问题13 —— Search Insert Position
- LeetCode——Search Insert Position
- LeetCode——Search Insert Position
- leetcode 035 —— Search Insert Position
- LeetCode35——Search Insert Position
- leetcode——Search Insert Position
- 二分查找——Search Insert Position
- 35. Search Insert Position —— Java
- <35>——Search Insert Position
- Algorithms—35.Search Insert Position
- [leetcode刷题系列]Search Insert Position
- 【Leetcode长征系列】Search Insert Position
- leetcode系列(49)Search Insert Position
- leetcode——Search Insert Position 二分查找 binary search
- 算法分析与设计——LeetCode Problem.35 Search Insert Position
- apache shiro框架如何使用nginx负载
- 百度地图-创建检索信息窗口对象
- java的数组知识
- 《魂斗罗:归来》卖“情怀”?不!质量体系来撑腰
- 机器学习(十二)
- 算法系列——Search Insert Position
- C++线程的几种调用方式
- Python学习笔记——深拷贝与浅拷贝
- android 代码规范文档(命名规范)
- <url-pattern>/</url-pattern>和<url-pattern>/*</url-pattern>区别 <url-pattern>/</url-pattern>表示的为只匹配/lo
- Android
- 基于深度学习的商品检索技术
- 《黑科技》
- win10完美去除快捷方式小箭头的方法