题解 | #数字在升序数组中出现的次数#

数字在升序数组中出现的次数

https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @param k int整型
     * @return int整型
     */
    public int GetNumberOfK (int[] nums, int k) {
        int count = 0;
        int leftIndex = leftMost(nums, k);
        int rightIndex = rightMost(nums, k);
        if (leftIndex == -1 || rightIndex == -1) {
            return 0;
        }
        count = rightIndex - leftIndex + 1;
        return count;
    }

    // 二分查找最左索引,找不到返回-1
    public int leftMost(int[] nums, int k) {
        // 在每次循环中记录找到的索引值
        int location = -1;
        if (nums.length == 0) {
            return location;
        }
        int pLeft = 0;
        int pRight = nums.length - 1;
        while (pLeft <= pRight) {
            int pMid = (pLeft + pRight) / 2;
            if (nums[pMid] < k) {
                // 目标在右半区域
                pLeft++;
            } else if (nums[pMid] > k) {
                // 目标在左半区域
                pRight--;
            } else {
                // 找到目标,更新索引值
                location = pMid;
                // 右边界减1,继续向左查找最左索引
                pRight--;
            }
        }
        return location;
    }

    // 二分查找最右索引,找不到返回-1
    public int rightMost(int[] nums, int k) {
        // 在每次循环中记录找到的索引值
        int location = -1;
        if (nums.length == 0) {
            return location;
        }
        int pLeft = 0;
        int pRight = nums.length - 1;
        while (pLeft <= pRight) {
            int pMid = (pLeft + pRight) / 2;
            if (nums[pMid] < k) {
                // 目标在右半区域
                pLeft++;
            } else if (nums[pMid] > k) {
                // 目标在左半区域
                pRight--;
            } else {
                // 找到目标,更新索引值
                location = pMid;
                // 左边界加1,继续向右查找最右索引
                pLeft++;
            }
        }
        return location;
    }
}

全部评论

相关推荐

真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务