当前位置:网站首页>【LeetCode每日一题】——704.二分查找
【LeetCode每日一题】——704.二分查找
2022-08-02 01:57: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]之间。
七【解题思路】
- 让我看看是谁还不会写二分查找?
八【时间频度】
- 时间复杂度: 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语言版
边栏推荐
猜你喜欢
密码学的基础:X.690和对应的BER CER DER编码
Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
typescript31-any类型
Garbage Collector CMS and G1
电子制造仓储条码管理系统解决方案
typescript35-class的构造函数
Fundamentals of Cryptography: X.690 and Corresponding BER CER DER Encodings
Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
三本毕业的我被腾讯拒绝了十四次,最终成功入职阿里
Constructor instance method inheritance of typescript37-class (extends)
随机推荐
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...
typescript32-ts中的typeof
LeetCode刷题日记:153、寻找旋转排序数组中的最小值
6-24漏洞利用-vnc密码破解
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
typescript38-class的构造函数实例方法继承(implement)
用位运算为你的程序加速
YGG 公会发展计划第 1 季总结
垃圾回收器CMS和G1
飞桨开源社区季度报告来啦,你想知道的都在这里
记录一次数组转集合出现错误的坑点,尽量使用包装类型数组进行转换
Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
Force buckle, 752-open turntable lock
Redis Subscription and Redis Stream
AntPathMatcher使用
oracle查询扫描全表和走索引
LeetCode刷题日记:LCP 03.机器人大冒险
MySQL optimization strategy
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
【图像融合】基于加权和金字塔实现图像融合附matlab代码