栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣35题+二分查找算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣35题+二分查找算法

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

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

核心思路:将问题转换成左侧查找的二分查找法(将等号并入大于的部分)

程序细节:

1.return的left 因为 最后一次循环时left = right = mid,如果nums[mid] < target 时 返回的应该是mid+1的下标,而当nums[mid] >= target 返回的就是mid的 , 因此应该使用left

算法详解 

二分查找法的细节:


1.考虑边界值

边界值分为跳出循环的条件边界值和查找时并入的边界值(例题展示的属于左侧查找的方法)

int left = 0, right = size; //关键在于 right = size 还是 size-1
while(left < right)  //相当于[left,right) , 如果为 size - 1 就是 [left,right]
{
    int mid = (left + right) / 2;
    if (a[mid] < target)
        {
           left = mid + 1; //利用区间理论,左边都闭说明应该再加一 
        }
    if (a[mid] > target)
        {
           right = mid; //还是利用区间理论,右边为开开区间不能为 mid-1 防止漏掉mid-1这个数 
        }
}

跳出循环边界可以利用开闭区间的理论。

2.算法思想

本质就是二分法的逼近方法,适用于排好序的插入和查找,对于这个问题的实现利用双指针,同时中间元素的索引 = (左边索引 + 右边索引)/ 2; 

在这里 /2 的操作保证奇数时找到中间数的索引,偶数时找到中间两数中左边的数再比较。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/644486.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号