zoukankan      html  css  js  c++  java
  • 剑指offer 53 -I 在排序数组中查找数字

    统计一个数字在排序数组中出现的次数。

    示例 1:

    输入: nums = [5,7,7,8,8,10], target = 8
    输出: 2

    示例 2:

    输入: nums = [5,7,7,8,8,10], target = 6
    输出: 0

    限制:

    0 <= 数组长度 <= 50000

    二分查找

    /**
     * 二分查找
     *
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return 0;
    
        int cnt = 0;
        int left = 0, right = nums.length - 1;
        int mid = left;
        while (left <= right) {
            mid = (left + right) >> 1;
            if (nums[mid] == target) break;
            else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        int index = mid;
        // 左侧
        while (index >= 0 && index < nums.length && nums[index] == target) {
            cnt++;
            index--;
        }
        index = mid + 1;
        // 右侧
        while (index >= 0 && index < nums.length && nums[index] == target) {
            cnt++;
            index++;
        }
        return cnt;
    }
    

    测试用例

    public static void main(String[] args) {
        int[] nums = new int[]{0};
        int target = 0;
        int cnt = SearchSecond.search(nums, target);
        System.out.println("SearchSecond demo01 result : " + cnt);
    
        nums = new int[]{5, 7, 7, 8, 8, 10};
        target = 8;
        cnt = SearchSecond.search(nums, target);
        System.out.println("SearchSecond demo02 result : " + cnt);
    
        nums = new int[]{5, 7, 7, 8, 8, 10};
        target = 6;
        cnt = SearchSecond.search(nums, target);
        System.out.println("SearchSecond demo03 result : " + cnt);
    
        nums = new int[]{1, 2, 3, 3, 3, 3, 4, 5, 9};
        target = 3;
        cnt = SearchSecond.search(nums, target);
        System.out.println("SearchSecond demo04 result : " + cnt);
    
        nums = new int[]{1, 2, 3};
        target = 1;
        cnt = SearchSecond.search(nums, target);
        System.out.println("SearchSecond demo05 result : " + cnt);
    }
    

    运行结果

  • 相关阅读:
    next_permutation函数(全排列)
    滚动数组
    多重背包问题
    ubuntu12.04硬盘安装
    UBUNTU12.04下安装配置体验gnome3
    给Ubuntu安装KDE桌面 [转]
    Ubuntu 13.04 用户安装 gnome 3.8 桌面
    ubuntu下安装wine
    ubuntu 安装输入法(fcitx)
    js 对url进行编码和解码的三种方式
  • 原文地址:https://www.cnblogs.com/fyusac/p/15019386.html
Copyright © 2011-2022 走看看