完美编程

Leetcode-二分法

2019-08-11  本文已影响0人  浩泽Hauser

Leetcode 1150. Check If a Number Is Majority Element in a Sorted Array. 【Easy】【Blue】
二分法找到等于target的最小的index,然后判断位于index后面半个数组位置的数是不是等于target。

class Solution {
    public boolean isMajorityElement(int[] nums, int target) {
        int left=0, right=nums.length-1;
        while(left<right){    // [ , )
            int mid = (right-left)/2+left;
            if(nums[mid] < target){
                left = mid+1;
            } else {
                right = mid;
            }
        }
        if(left+nums.length/2 < nums.length && nums[left+nums.length/2]==target){
            return true;
        }
        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读