当前位置:网站首页>【LeetCode Daily Question】——704. Binary Search
【LeetCode Daily Question】——704. Binary Search
2022-08-02 02:00:00 【IronmanJay】
一【题目类别】
- 二分查找
二【题目难度】
- 简单
三【题目编号】
- 704.二分查找
四【题目描述】
- 给定一个 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]之间.
七【解题思路】
- Let me see who can't write binary search yet?
八【时间频度】
- 时间复杂度: O ( l o g 2 N ) O(log_{2}N) O(log2N),其中 N N N为数组元素个数
- 空间复杂度: O ( 1 ) O(1) O(1)
九【代码实现】
- Java语言版
package BinarySearch;
public class p704_BinarySearch {
public static void main(String[] args) {
int[] nums = {
-1, 0, 3, 5, 9, 12};
int res = search(nums, 9);
System.out.println("res = " + res);
}
public static int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
return -1;
}
}
- C语言版
#include<stdio.h>
int p704_BinarySearch_search(int* nums, int numsSize, int target)
{
int left = 0;
int right = numsSize - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] > target)
{
right = mid - 1;
}
else if (nums[mid] < target)
{
left = mid + 1;
}
}
return -1;
}
/*主函数省略*/
十【提交结果】
Java语言版

C语言版

边栏推荐
- 飞桨助力航天宏图PIE-Engine地球科学引擎构建
- 『网易实习』周记(一)
- ofstream,ifstream,fstream读写文件
- Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
- Data transfer at the data link layer
- Constructor of typescript35-class
- Moonbeam与Project Galaxy集成,为社区带来全新的用户体验
- 一本适合职场新人的好书
- PHP 使用 PHPRedis 与 Predis
- AOF重写
猜你喜欢
随机推荐
一本适合职场新人的好书
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
volatile原理解析
Constructor of typescript35-class
"NetEase Internship" Weekly Diary (2)
力扣、752-打开转盘锁
【轮式里程计】
电商库存系统的防超卖和高并发扣减方案
typescript31-any类型
AntPathMatcher使用
大话西游创建角色失败解决
C语言之插入字符简单练习
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
pcie inbound和outbound关系
哈希表
求大神解答,这种 sql 应该怎么写?
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
MySQL优化策略
『网易实习』周记(三)
Day116. Shangyitong: Details of appointment registration ※









