本文主要是介绍LeetCode 704. Binary Search(二分查找),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
Given a sorted (in ascending order) integer array numsof n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
Example 1:
Input:nums = [-1,0,3,5,9,12],target = 9Output: 4 Explanation: 9 exists in nums and its index is 4
Example 2:
Input:nums = [-1,0,3,5,9,12],target = 2Output: -1 Explanation: 2 does not exist in nums so return -1
Note:
- You may assume that all elements in
numsare unique. nwill be in the range[1, 10000].- The value of each element in
numswill be in the range[-9999, 9999].
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 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
提示:
- 你可以假设
nums中的所有元素是不重复的。 n将在[1, 10000]之间。nums的每个元素都将在[-9999, 9999]之间。
思路:
最基本的二分查找算法!直接背过!!!
实现(C++):
1. 非递归算法
class Solution {
public:int search(vector<int>& nums, int target) {int low=0;int high=nums.size()-1;int mid;while(low<=high) {mid=low+(high-low)/2;if(nums[mid]==target) return mid;else if(target<nums[mid])high=mid-1;else if(target>nums[mid])low=mid+1;}return -1;}
};
2. 递归算法
class Solution {public:int Search_Bin_Re(vector<int>& nums, int target, int low, int high) {if(low>high)return -1;int mid=low+(high-low)/2;if(target==nums[mid])return mid;else if(target<nums[mid])return Search_Bin_Re(nums, target, low, mid-1);elsereturn Search_Bin_Re(nums, target, mid+1, high);}public:int search(vector<int>& nums, int target) {return Search_Bin_Re(nums, target, 0, nums.size()-1);}
};
这篇关于LeetCode 704. Binary Search(二分查找)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!