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.

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;elsel = 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;elsel = mid + 1;}}//return l;}没错,就是只有一行不一样,就是下面的代码我注释了一行,但是两个代码均可以AC,

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

或者可能返回默认值0;

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

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

因为在路上你就已经收获了自由自在的好心情。

LeetCode 35 Search Insert Position

相关文章:

你感兴趣的文章:

标签云: