首页 > 代码库 > LeetCode Problem 35:Search Insert Position
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 else17 end = mid - 1;18 }19 20 if(target > A[mid])21 return mid + 1;22 else23 return mid;24 25 }26 };
LeetCode Problem 35:Search Insert Position
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。