6

#yyds干货盘点# 面试必刷TOP101:二分查找-I

 2 years ago
source link: https://blog.51cto.com/u_15488507/5563491
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 面试必刷TOP101:二分查找-I

原创

97的风 2022-08-10 14:00:57 博主文章分类:面试题 ©著作权

文章标签 整型 数组 升序 文章分类 Java 编程语言 阅读数194

1.简述:

描述

请实现无重复数字的升序数组的二分查找

给定一个 元素升序的、无重复数字的整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标(下标从 0 开始),否则返回 -1

数据范围: , 数组中任意值满足 

进阶:时间复杂度  ,空间复杂度 

示例1
[-1,0,3,4,6,10,13,14],13
13 出现在nums中并且下标为 6
示例2
nums为空,返回-1
示例3
[-1,0,3,4,6,10,13,14],2
2 不存在nums中因此返回 -1

2.代码实现:

import java.util.*;


public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search (int[] nums, int target) {
// write code here
int left = 0, right = nums.length - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] == target){
return mid;
} else if(nums[mid] > target){
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK