leetcode 35 :Search Insert Position
题目链接: https://leetcode-cn.com/problems/search-insert-position/
难度: 简单
归类 : 数组操作 二分查找
题目:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例:
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例?2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
解法:
主要使用c++和python等两种语言进行了解答,以及经典题解和尝试改进的最优/最简洁解法。
个人解法
c++解法
//c++解法
//进行一次for循环,判断nums[i]和target之间的关系。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
if(len == 0) return 0;
for(int i = 0; i < len; i++){
if(nums[i] >= target){
return i;
}
}
return len;
}
};
时间复杂度: O(N)
空间复杂度: O(1 )
提交结果:
执行用时 :4 ms, 在所有 C++ 提交中击败了95.23%的用户
内存消耗 :6.6 MB, 在所有 C++ 提交中击败了100.00%的用户
//二分法,经典二分求插入位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
if(len == 0) return 0;
int start = 0;
int end = nums.size();
int mid;
while(start < end){
mid = start + (end - start) / 2;
if(nums[mid] > target){
end = mid;
}else if(nums[mid] < target){
start = mid + 1;
}else{
return mid;
}
}
return start;
}
};
时间复杂度: O(NlogN)
空间复杂度: O(1)
提交结果:
执行用时 :8 ms, 在所有 C++ 提交中击败了50.19%的用户
内存消耗 :6.7 MB, 在所有 C++ 提交中击败了100.00%的用户
python解法
#python解法
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
start = 0
end = length
while start < end:
mid = start + (end - start) / 2
if nums[mid] > target:
end = mid
elif nums[mid] < target:
start = mid + 1
else:
return mid
return start
时间复杂度: O(NlogN)
空间复杂度: O(1)
提交结果:
执行用时 :20 ms, 在所有 Python 提交中击败了79.51%的用户
内存消耗 :13 MB, 在所有 Python 提交中击败了7.14%的用户
题解优解
此题解法:
暴力法,一次for循环遍历(O(N),O(1))
二分法(O(NlogN), O(1))
尝试改进的最优解法
https://leetcode-cn.com/problems/search-insert-position/solution/te-bie-hao-yong-de-er-fen-cha-fa-fa-mo-ban-python-/