查找排序数组的插入位置
2013-04-25 15:47
375 查看
题目:
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.
分析:此题和上一题类似,就是利用二分搜索查找数字。
具体代码如下:
int searchInsert(int A[], int n, int target) {
if(n<=0)return 0;
int l=0,r=n-1,m=l+(r-l)/2;
while(l<r)
{
if(A[m]>=target)r=m;
if(A[m]<target)l=m+1;
m=l+(r-l)/2;
}
if(A[m]>=target)
return m;
return m+1;
}
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
分析:此题和上一题类似,就是利用二分搜索查找数字。
具体代码如下:
int searchInsert(int A[], int n, int target) {
if(n<=0)return 0;
int l=0,r=n-1,m=l+(r-l)/2;
while(l<r)
{
if(A[m]>=target)r=m;
if(A[m]<target)l=m+1;
m=l+(r-l)/2;
}
if(A[m]>=target)
return m;
return m+1;
}
相关文章推荐
- 9.11排序与查找(二)——对字符串数组进行排序,将全部的变位词排在相邻的位置
- 在排序好的数组插入一个数字,数字要插入到合适的位置上
- 在排序的数组中二分查找一个元素,返回在数组中它第一次出现的位置
- 关于动态存储分配函数的调用,在已经过排序的数组中查找及删除内容的操作,余数的分析,删除字符数组中的空格,对链表的逆置,在源字符串中查找子字符串的个数,函数指针以及函数的调用,循环赋值带来的问题以及插入
- 大二 第一次数据结构作业 (数组的排序,删除,查找,插入,合并)(线性表)
- c语言心得-----数组中对元素的操作排序,查找,插入,和删除
- 9.11排序与查找(二)——对字符串数组进行排序,将所有的变位词排在相邻的位置
- 插入元素到有序数组,二分搜索查找插入位置
- 一个数组 输入一个数 查找到它的位置 插入合适的位置
- Leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
- python_lintcode_64合并排序数组 II_60搜索插入位置_142 O(1)时间检测2的幂次
- 33.在旋转排序的数组中查找某值位置
- 9.11排序与查找(五)——有个排序后的字符串数组,其中散布着一些空字符串,找出给定字符串的位置
- 在排序好的数组插入一个数字,数字要插入到合适的位置上
- 程序员面试金典: 9.11 排序与查找 11.1编写一个方法,对字符串数组进行排序,将所有变位词排在相邻的位置。
- java程序:在排序好的数组中添加一个数字,将添加后的数字插入到数组合适的位置。怎么写啊?
- 剑指offer——面试题38:数字在排序数组中出现的次数(利用二分查找来找第一次和最后一次的位置)
- 在排序好的数组插入一个数字,数字要插入到合适的位置上
- javascript 常见数组操作( 1、数组整体元素修改 2、 数组筛选 3、jquery 元素转数组 4、获取两个数组中相同部分或者不同部分 5、数组去重并倒序排序 6、数组排序 7、数组截取slice 8、数组插入、删除splice(需明确位置) 9、数组遍历 10、jQuery根据元素值删除数组元素的方)
- 程序员面试金典: 9.11 排序与查找 11.5有个排序后的字符串数组,其中散布这一些空字符串,编写一个方法,找出给定字符串的位置