来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-search/
题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target, 如果目标值存在返回下标,否则返回 -1。
题目分析
本题是最基础的二分查找。
代码实现
public class ErFenChaZhao_704 {
public static void main(String[] args) {
ErFenChaZhao_704 erFenChaZhao_704 = new ErFenChaZhao_704();
int[] nums = {-1, 0, 3, 5, 9, 12};
int target = 9;
erFenChaZhao_704.search(nums, target);
}
public int search(int[] nums, int target) {
int leftIndex = 0;
int rightIndex = nums.length - 1;
while (leftIndex <= rightIndex) {
int midIndex = (rightIndex + leftIndex) / 2;
if (nums[midIndex] == target) {
return midIndex;
} else if (nums[midIndex] > target) {
rightIndex = midIndex;
} else {
leftIndex = midIndex + 1;
}
}
return -1;
}
}
复杂度
- 时间复杂度:O(logn),其中 n 是定版本的数量。
- 空间复杂度:O(1),只需要常数的空间保存变量。
好了,今天就到这里,感谢各位看官到这里,不如点个关注吧!