LeetCode --- 35. Search Insert Position
2015-02-04 23:19
477 查看
题目链接: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.
这道题的要求是在一个有序数组中,找到给定的target在数组中出现的位置。如果不存在,返回插入target元素后仍使数组有序的插入位置。可以假设数组中没有重复元素。
和Search for a Range类似,同样采用二分搜索。在target等于A[m]的时候,可以采取和target小于A[m]情况同样的操作,即r=m-1,这样可以确保最后l就是target出现的位置或是target插入的位置。
时间复杂度:O(logn)
空间复杂度:O(1)
转载请说明出处:LeetCode --- 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.
[code][1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0
这道题的要求是在一个有序数组中,找到给定的target在数组中出现的位置。如果不存在,返回插入target元素后仍使数组有序的插入位置。可以假设数组中没有重复元素。
和Search for a Range类似,同样采用二分搜索。在target等于A[m]的时候,可以采取和target小于A[m]情况同样的操作,即r=m-1,这样可以确保最后l就是target出现的位置或是target插入的位置。
时间复杂度:O(logn)
空间复杂度:O(1)
[code] 1 class Solution 2 { 3 public: 4 int searchInsert(int A[], int n, int target) 5 { 6 int l = 0, r = n - 1, m; 7 while(l <= r) 8 { 9 m = (l + r) / 2; 10 if(target <= A[m]) 11 r = m - 1; 12 else 13 l = m + 1; 14 } 15 return l; 16 } 17 };
转载请说明出处:LeetCode --- 35. Search Insert Position
相关文章推荐
- LeetCode 35 Search Insert Position 二分法处理
- LeetCode_35---Search Insert Position
- [leetcode] 35. Search Insert Position
- 【LeetCode35】【Search Insert Position】二分法查找
- 35. Search Insert Position LeetCode
- 【LeetCode 35】Search Insert Position(Python)
- [LeetCode35]Search Insert Position
- leetcode-35 Search Insert Position
- Leetcode_35_Search Insert Position
- leetcode(35) - Search Insert Position
- [LeetCode-35] Search Insert Position(二分法)
- leetcode 35 Search Insert Position
- 【LeetCode】C# 35、Search Insert Position
- LeetCode 35 Search Insert Position
- LeetCode-35-Search Insert Position(C语言实现)
- leetcode.array--35. Search Insert Position
- leetcode-- 35. Search Insert Position
- 35. Search Insert Position leetcode Python 2016 new season
- [leetcode 35] Search Insert Position
- LeetCode@Array_35_Search_Insert_Position