首页 > 代码库 > First Occurrence Of Binary Search

First Occurrence Of Binary Search

和普通的binary search不同就是在处理找到等于target的数

首先要记录这个结果,然后我们现在其实是需要向左找,右边的数都不重要,因为我们要找最左出现的,我们就假设现在的情况是nums[mid] > target,所以high = mid - 1.如果找不到了,那么之前的结果就是最左侧的,否则就继续找。

 1     public int firstOccurence(int[] nums, int target) { 2         int left = 0; 3         int right = nums.length - 1; 4         int res = -1; 5         while(left <= right) { 6             int mid = left + (right - left) / 2; 7             if(nums[mid] == target) { 8                 res = mid; 9                 right = mid - 1;10             } else if(nums[mid] < target) {11                 left =  mid + 1;12             } else {13                 right = mid - 1;14             }15         }16         return res;17     }

 

First Occurrence Of Binary Search