当前位置:网站首页>【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语言版

边栏推荐
猜你喜欢

Navicat数据显示不完全的解决方法

typescript33-typescript高级概述

6-24 exploit-vnc password cracking

Local storage in Kubernetes

Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits

Check if IP or port is blocked

Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序

Redis 底层的数据结构

HSDC is related to Independent Spanning Tree

大话西游创建角色失败解决
随机推荐
typescript33 - high-level overview of typescript
6-24 exploit-vnc password cracking
当关注「互联网+」模式的时候,通常仅仅只是在关注「互联网+」模式本身
typescript30 - any type
【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例
PHP直播源码实现简单弹幕效果的相关代码
Effects of Scraping and Aggregation
"NetEase Internship" Weekly Diary (1)
【ORB_SLAM2】void Frame::AssignFeaturesToGrid()
When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
Day116. Shangyitong: Details of appointment registration ※
60种特征工程操作:使用自定义聚合函数【收藏】
3个月测试员自述:4个影响我职业生涯的重要技能
Day116.尚医通:预约挂号详情 ※
LeetCode brushing diary: 33. Search and rotate sorted array
hash table
秒懂大模型 | 3步搞定AI写摘要
Data transfer at the data link layer
Moonbeam与Project Galaxy集成,为社区带来全新的用户体验
【Brush the title】Family robbery