LeetCode --Search Insert Position
来源:互联网 发布:淘宝客日赚 编辑:程序博客网 时间:2024/06/05 17:42
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:直观的想法,遍历数组,一旦当前元素>=target,当前元素的位置即为插入位置,边界问题处理一下即可。时间复杂度:O(n)
class Solution {public: int searchInsert(int A[], int n, int target) { if(target > A[n-1]) return n; else { for(int i = 0; i < n; i++) { if(A[i] >= target) return i; } } }};
思路2:由于给定数组为已经排好序的,可以使用二分查找,比较A[mid]与target的大小。时间复杂度:O(logn)
class Solution {public: int searchInsert(int A[], int n, int target) { int start = 0; int end = n - 1; int mid = 0; while(end >= start) { mid = (start + end) / 2; if(target == A[mid]) return mid; else if(target > A[mid]) start = mid + 1; else end = mid - 1; } if(target > A[mid]) return mid + 1; else return mid; }};
0 0
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode-Search Insert Position
- LeetCode - Search Insert Position
- LeetCode | Search Insert Position
- Leetcode: Search Insert Position
- 【LeetCode】Search Insert Position
- Leetcode Search Insert Position
- Leetcode: Search Insert Position
- LeetCode:Search Insert Position
- leetcode Search Insert Position
- LeetCode Search Insert Position
- 工作效率有感
- 黑马程序员——Objective-C学习笔记(六):内存管理
- jquery datepicker在局部刷新之后保持有效
- java内部类
- LeetCode Palindrome Number回文数
- LeetCode --Search Insert Position
- 转载:HDFS小文件问题及解决方案
- Single Number---leetcode c# solution
- 转载:Hadoop Streaming 编程
- maven教程初稿
- Linux装载和执行可执行程序的分析
- The Proccess of Loading and Executing a Specific Program in Linux Kernel
- 二分查找算法实例注释
- Linux下vim配置文件