LeetCode 35 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.

题目描述:

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


题目翻译:

给定一个排序数组和一个目标价值,如果找到目标返回索引。如果没有找到,返回待插入位置的索引

你可能认为数组内的元素没有重复。


解题思路:标准的二分查找,请仔细观察下面两个代码:


C语言版:

int searchInsert(int A[], int n, int target) {
    int l = 0, r = n - 1, mid;
    while(l <= r){
		mid = (l + r) >> 1;
		if (target == A[mid]) return mid;
		else{
			if(target < A[mid])
				r = mid - 1;
			else
				l = mid + 1;
		}
	}
	return l;
}
C语言版:

int searchInsert(int A[], int n, int target) {
    int l = 0, r = n - 1, mid;
    while(l <= r){
		mid = (l + r) >> 1;
		if (target == A[mid]) return mid;
		else{
			if(target < A[mid])
				r = mid - 1;
			else
				l = mid + 1;
		}
	}
	//return l;
}
没错,就是只有一行不一样,就是下面的代码我注释了一行,但是两个代码均可以AC,

是的,第二个如果去掉最后的return l; 函数如果在数组A中找不到元素target,应该不会返回值,

或者可能返回默认值0;

但是结果却出乎意料,返回的结果竟然也是l ;或者说刚好和l一样大,至少我能确定返回的不是mid和r,

看到文章的大神们,如果知道原因的还望给予解答,在此提前谢过!

目录
相关文章
|
10月前
Leetcode 74. Search a 2D Matrix
这道题很简单,为此专门写篇博客其实算博客凑数了。给你一个每一行每一列都是增序,且每一行第一个数都大于上一行末尾数的矩阵,让你判断某个数在这个矩阵中是否存在。 假设矩阵是m*n,扫一遍的时间复杂度就是O(m*n),题目中给出的这么特殊的矩阵,时间复杂度可以降到O(m+n),具体代码如下,写的比较挫。
76 1
|
存储 索引
LeetCode 381. Insert Delete GetRandom O1 Dallowed
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。
71 0
LeetCode 381. Insert Delete GetRandom O1 Dallowed
|
存储 索引
LeetCode 380. Insert Delete GetRandom O1
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
42 0
LeetCode 380. Insert Delete GetRandom O1
LeetCode 212. Word Search II
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
69 0
LeetCode 212. Word Search II
|
索引
LeetCode 81. Search in Rotated Sorted Array II
假设按升序排序的数组在事先未知的某个枢轴处旋转。 (例如, [0,0,1,2,2,5,6] 可能变成 [2,5,6,0,0,1,2]). 给定一个要搜索的目标值T, 如果该目标值能在数组中找到则返回true,否则返回false。
81 0
LeetCode 81. Search in Rotated Sorted Array II
|
索引
LeetCode 79. Word Search
给定一个2D板和一个单词,找出该单词是否存在于网格中。 该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。 相同的字母单元格不得多次使用。
67 0
LeetCode 79. Word Search
|
算法
LeetCode 74. Search a 2D Matrix
编写一个有效的算法,搜索m×n矩阵中的值。 此矩阵具有以下属性: 每行中的整数从左到右排序. 每行的第一个整数大于前一行的最后一个整数.
69 0
LeetCode 74. Search a 2D Matrix
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
机器学习/深度学习
Leetcode-Medium 96.Unique Binary Search Trees
Leetcode-Medium 96.Unique Binary Search Trees
88 0
|
算法 Python
Leetcode-Medium 98. Validate Binary Search Tree
Leetcode-Medium 98. Validate Binary Search Tree
121 0