leetcode 704 :Binary Search
题目链接: https://leetcode-cn.com/problems/binary-search/
难度: 简单
归类 : 数组操作 二分查找
题目
给定一个?n?个元素有序的(升序)整型数组?nums 和一个目标值?target ?,写一个函数搜索?nums?中的 target,如果目标值存在返回下标,否则返回 -1。
你可以假设 nums 中的所有元素是不重复的。
n 将在 [1, 10000]之间。
nums 的每个元素都将在 [-9999, 9999]之间
示例:
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例?2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
解法
主要使用c++和python等两种语言进行了解答,以及经典题解和尝试改进的最优/最简洁解法。
本题目是标准的二分法题目
个人解法
C++解法
//c++解法
//二分法
class Solution {
public:
int search(vector<int>& nums, int target) {
int len = nums.size();
int start = 0, end = len, mid;
while(start < end){
mid = start + (end - start) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) end = mid;
else start = mid + 1;
}
return -1;
}
};
时间复杂度: O(NlogN)
空间复杂度: O(1)
提交结果:
执行用时 :88 ms, 在所有 C++ 提交中击败了37.56%的用户
内存消耗 :25.6 MB, 在所有 C++ 提交中击败了5.88%的用户
//另外一种边界条件的二分法
class Solution {
public:
int search(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
while(l<=r)
{
int m=(r-l)/2+l;
if(nums[m]>target)
{
r=m-1;
}
else if(nums[m]<target)
{
l=m+1;
}
else
return m;
}
return -1;
}
};
时间复杂度: O(NlogN)
空间复杂度: O(1)
提交结果:
执行用时 :88 ms, 在所有 C++ 提交中击败了37.56%的用户
内存消耗 :25.6 MB, 在所有 C++ 提交中击败了5.88%的用户
python解法
#python解法
class Solution(object):
def search(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:
return mid
elif nums[mid] > target:
end = mid
else:
start = mid + 1
return -1
时间复杂度: O(NlogN)
空间复杂度: O(1)
提交结果:
执行用时 :248 ms, 在所有 Python 提交中击败了78.71%的用户
内存消耗 :13.7 MB, 在所有 Python 提交中击败了14.29%的用户
题解优解
此题解法:
二分法(O(NlogN), O(1))