Search Insert Position
来源:互联网 发布:java如何合并两个list 编辑:程序博客网 时间:2024/04/27 14:47
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)利用二分查找,时间复杂度为O(n*logn)。
(2)注意一些边界条件,当target < A[0]时候,返回为0,当target > A[n-1]的时候返回为n。
#include <iostream>using namespace std; int searchInsert(int A[], int n, int target) {int begin = 0;int end = n-1;if(target < A[0])return 0;if(target > A[n-1])return n;if(n==0)exit(1);while(begin < end){int mid = (begin+end)/2;if(A[mid] == target)return mid;if(A[mid] > target){end = mid - 1;}if(A[mid] < target){begin = mid + 1;}}if(target > A[end])return end+1;if(target <= A[end])return end;}int main(void){int A[] = {1,3};cout << searchInsert(A, 2, 0) << endl; system("pause");return 0;}
0 0
- LeetCode: Search Insert Position
- Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode34:Search Insert Position
- Search Insert Position
- [35]Search Insert Position
- Search Insert Position
- Search Insert Position
- [LeetCode]Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- Search Insert Position
- Search Insert Position
- win7 下注册dll文件失败分析
- arm--ldm、stm指令解析
- 早该知道的7个JavaScript技巧
- android listview addHeaderView入参不同的区别
- 图文介绍如何在Eclipse统计代码行数
- Search Insert Position
- 二分查找中的死循环
- 数据结构 第一章 绪论
- 归并排序
- 软工——详解白盒测试
- 哲学家吃饭
- gc overhead limit exceeded eclipse解决方案
- 使用queryperf对DNS服务器作压力测试
- C语言-ATM机