【LeetCode】Search Insert Position

本文深入解析了C++中关于在已排序数组中搜索插入位置的问题,提供了详细的二分查找变形算法分析,并附上了实际代码示例,帮助读者理解和实现这一核心算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

Search Insert Position

 

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


题目分析

二分查找的变形,不多说

总结

理解在不存在时的返回值应该是多少。

代码示例


/*
编译环境CFree 5.0
博客地址:http://blog.youkuaiyun.com/Snowwolf_Yang
*/
#include 
   
    

using namespace std;

#if 0 
class Solution {
public:
    int searchInsert(int A[], int n, int target) {
    	if(n == 0)	return 0;
        if(n == 1)
        {
        	if(A[0] < target) 	return 1;
        	else 				return 0;
		}
		int mid = n/2;
		if(A[mid]
    
     target)
				return searchInsert(&A[0],mid,target);
		else
			return mid;
    }
};
#elif 1
class Solution {
public:
    int searchInsert(int A[], int n, int target) {
    	if(n == 0)	return 0;
		int start = 0, end = n - 1;
		while(start <= end)
		{
			int mid = (start + end)/2;
			if(A[mid]
     
      target)
				end = mid - 1;
			else 
				return mid;
		}
		return start;					//这一点需要理解透彻 
    }
};
#endif
void test0()
{
	int a[] = {1,3,5,6}; 
	int n = 4;
	int target = 5;
	int expected = 2;
	Solution so;
	if(so.searchInsert(a,n,target) == expected)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
void test1()
{
	int a[] = {1,3,5,6}; 
	int n = 4;
	int target = 2;
	int expected = 1;
	Solution so;
	if(so.searchInsert(a,n,target) == expected)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
void test2()
{
	int a[] = {1,3,5,6}; 
	int n = 4;
	int target = 7;
	int expected = 4;
	Solution so;
	if(so.searchInsert(a,n,target) == expected)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
void test3()
{
	int a[] = {1,3,5,6}; 
	int n = 4;
	int target = 0;
	int expected = 0;
	Solution so;
	if(so.searchInsert(a,n,target) == expected)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
void test4()
{
	int a[] = {1,3}; 
	int n = 2;
	int target = 0;
	int expected = 0;
	Solution so;
	if(so.searchInsert(a,n,target) == expected)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
int main()
{
	test0();
	test1();
	test2();
	test3();
	test4();
	return 0;
}
 

     
    
   

推荐学习C++的资料

C++标准函数库
在线C++API查询
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值