LeetCode34. Find First and Last Position of Element in Sorted Array

    xiaoxiao2025-06-09  27

    用二分查找的思想先找到数组中第一个等于target的数,如果没找到直接返回{-1,-1},如果找到了,left就确定了,然后在找最右边的数,记为right,得出答案。

    class Solution { public int[] searchRange(int[] nums, int target) { int[] res={-1,-1}; res[0]=help(target,nums,true); if(res[0]==nums.length || nums[res[0]]!=target){ res[0]=-1; return res; } res[1]=help(target,nums,false)-1; return res; } public int help(int target,int[] nums,boolean left){ int lo=0; int high=nums.length; while(lo<high){ int mid=(lo+high)/2; if(nums[mid]>target || (left&&nums[mid]==target)){ high=mid; } else lo=mid+1; } return lo; } }

     

    最新回复(0)