欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Leetcode:34(二分查找)

Leetcode:34(二分查找)

2025/3/15 20:44:26 来源:https://blog.csdn.net/YuZeH/article/details/146257563  浏览:    关键词:Leetcode:34(二分查找)

一,题目

二,思路

  • 找到最左和最右俩个点,利用俩个二分查找
  • 俩种情况一种存在一种不存在
  • 存在:nums[m]==target右边-1  结果i
  • 存在:nums[m]==target左边+1  但是结果下标减去i-1
  • 上面俩种情况可以举例子 1 2 2 3 找2 自己推理一下就明白
  • 不存在:一种情况nums为空的情况 一种是数据没找到

三,代码

import java.util.Arrays;public class Leetcode34 {public static void main(String[] args) {System.out.println(Arrays.toString(new Leetcode34().searchRange(new int[]{1}, 1)));}public int[] searchRange(int[] nums, int target) {int[] arr = new int[2];arr[0] = left(nums, target);if (arr[0] == -1)arr[1] = -1;elsearr[1] = right(nums, target);return arr;}public int left(int[] nums, int target) {if (nums.length > 0) {int i = 0;int j = nums.length - 1;while (i <= j) {int m = (i + j) >>> 1;if (nums[m] < target) {//左i = m + 1;} else {j = m - 1;}}if (i < nums.length && nums[i] == target) return i;}return -1;}public int right(int[] nums, int target) {if (nums.length > 0) {int i = 0;int j = nums.length - 1;while (i <= j) {int m = (i + j) >>> 1;if (nums[m] <= target) {//左i = m + 1;} else {j = m - 1;}}if (i - 1 < nums.length && nums[i - 1] == target) return i - 1;}return -1;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词