当前位置:网站首页>【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语言版
边栏推荐
- Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
- Kubernetes之本地存储
- Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
- 3 Month Tester Readme: 4 Important Skills That Impacted My Career
- Data transfer at the data link layer
- For effective automated testing, these software testing tools must be collected!!!
- Shell入门终章
- 【Brush the title】Family robbery
- 『网易实习』周记(二)
- 6-24 exploit-vnc password cracking
猜你喜欢
随机推荐
Day116.尚医通:预约挂号详情 ※
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
求大神解答,这种 sql 应该怎么写?
搜罗汇总的效应
Constructor instance method inheritance of typescript37-class (extends)
『网易实习』周记(一)
电商库存系统的防超卖和高并发扣减方案
6-24 exploit-vnc password cracking
bool Frame::PosInGrid(const cv::KeyPoint &kp, int &posX, int &posY)
HSDC和独立生成树相关
LeetCode刷题日记:153、寻找旋转排序数组中的最小值
5年自动化测试经验的一些感悟:做UI自动化一定要跨过这10个坑
Effects of Scraping and Aggregation
LeetCode刷题日记:74. 搜索二维矩阵
AOF rewrite
typescript29-枚举类型的特点和原理
ofstream,ifstream,fstream读写文件
hash table
Coding Experience Talk
LeetCode刷题日记:53、最大子数组和