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
入门级题目。
思路有两个:
1 二分法查找到该数值,然后前移到比前面的数大的位置。如果没有找到就返回第一个比该数值大的数的下标。
2 可以二分法查找,不过稍微修改一下,例如查找1,3,5,6;那么两个坐标位置是0和3,然后计算中间位置m = (0+3)/2;但是这里要修改为(0+3+1)/2;这个是关键的地方。因为这样就截去了大于等于这个值的数,那么最后循环返回前面的指针(下标),就可以找到第一个大于等于该数值的下标了。
第一个思路很简单,这里只用了第二个思路,下面是二分法递归查找:
int searchInsert(int A[], int n, int target)
{
return lowerBound(A, 0, n-1, target);
}
int lowerBound(int A[], int front, int back, int tar)
{
if (front > back) return front;
int mid = front + ((back-front+1)>>1);
if (A[mid] < tar)
return lowerBound(A, mid+1, back, tar);
return lowerBound(A, front, mid-1, tar);
}
下面是非递归的:
class Solution {
public:
int searchInsert(int A[], int n, int target)
{
int first = 0;
while (n>0)
{
//注意:移位操作的优先级,注意都加括号
int mid = first + (n>>1);
if (A[mid] < target)
{
first = mid+1;
n -= (n>>1)+1;
}
else n >>= 1;
}
return first;
}
};
2014元旦更新:
二分截断法:
int searchInsert3(int A[], int n, int target)
{
int low = 0, up = n-1, mid = 0;
while (low <= up)
{
mid = low +((up-low)>>1);
if (A[mid] >= target) up = mid-1;
else low = mid+1;
}
return low;
}
不能再改进的程序了
//2014-1-26 update
int searchInsert(int A[], int n, int target)
{
int low = 0, up = n-1;
while (low <= up)
{
int mid = low + ((up-low)>>1);
if (A[mid] >= target) up = mid-1;
else low = mid+1;
}
return low;
}
分享到:
相关推荐
c++ c++_c++编程基础之leetcode题解第57题插入区间
c++_c++编程基础之leetcode题解第35题搜索插入位置
二分查找Binary_Search套路和解题模板【LeetCode刷题套路教程3】
虽然题目是很简单,但是对于细节进行了补充
704.Binary_Search二分查找【LeetCode单题讲解系列】
如果目标值不存在于数组中,返回它将会被按顺序插入的位置 使用二分查找,需要注意一般二分查找结束循环的条件是start 在本题中,当start=end时需要额外判断当前值跟target的大小,target大则返回start+1,否则返回...
刷LeetCode刷LeetCode刷LeetCode刷LeetCode刷LeetCode
python python_leetcode面试题解之第35题搜索插入位置_python题解
"interleaving_string.erl","search_insert_position.erl", "three_sum.erl","trapping_rain_water.erl", "valid_palindrome.erl" 个人认为dungeon_game这个题目解题逻辑很体现erlang的函数式的思维逻辑
LeetCode 问题 34 要求在一个增序的整数数组中找出给定目标值的开始和结束位置。如果数组中不存在目标值,返回 [-1, -1]。这个问题可以通过两次二分查找来解决:一次查找目标值开始的位置,另一次查找结束的位置。 ...
leetcode中文版
vs code LeetCode 插件
1. Introduction 2. Array i. Remove Element ii. Remove Duplicates from Sorted Array iii....iv....v....vi....vii....viii....ix....x....xi. Search a 2D Matrix xii.... Search Insert Position xiv. Find Peak Element
100个leetCode详细解答
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101.zip
大佬的leetcode刷题笔记(c++版本)
LeetCode 刷题汇总1
LeetCode 选讲1
LeetCode 101_C++_算法_leetcode_leetcode101_leetcode101_源码.zip