LeetCode Problem 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

思路1:直观的想法,遍历数组,一旦当前元素>=target,当前元素的位置即为插入位置,边界问题处理一下即可。时间复杂度:O(n)

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4 
 5         if(target > A[n-1])
 6             return n;
 7             
 8         else    {        
 9             for(int i = 0; i < n; i++)  {
10                 if(A[i] >= target)
11                     return i;
12             }
13         }
14     }
15 };

 

思路2:由于给定数组为已经排好序的,可以使用二分查找,比较A[mid]与target的大小。时间复杂度:O(logn)

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4         
 5         int start = 0;
 6         int end = n - 1;
 7         int mid = 0;
 8         
 9         while(end >= start)  {
10             
11             mid = (start + end) / 2;
12             if(target == A[mid])
13                 return mid;
14             else if(target > A[mid])
15                 start = mid + 1;
16             else
17                 end = mid - 1;
18         }
19         
20         if(target > A[mid])
21             return mid + 1;
22         else
23             return mid;
24 
25     }
26 };

 

转载于:https://www.cnblogs.com/fanyabo/p/4180817.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值