• LinCode 14.二分查找


    public class BinarySearch {
        /**
         * @param nums:   The integer array.
         * @param target: Target to find.
         * @return: The first position of target. Position starts from 0.
         * <p>
         * 14.二分查找
         * 给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1。
         * <p>
         * 样例
         * 在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2。
         * <p>
         * 挑战
         * 如果数组中的整数个数超过了2^32,你的算法是否会出错?
         */
        public int binarySearch(int[] nums, int target) {
            // write your code here
            return binSearch(nums, target, 0, nums.length);
        }
    
        public int binSearch(int[] nums, int target, int i, int j) {
            if (i > j) {
                return -1;
            }
            if (target == nums[(i + j) / 2]) {
                int k = (i + j) / 2;
                while (k >= 1 && nums[k - 1] == nums[k]) {
                    k--;
                }
                return k;
            } else if (target < nums[(i + j) / 2]) {
                return binSearch(nums, target, i, (i + j) / 2 - 1);
            } else {
                return binSearch(nums, target, (i + j) / 2 + 1, j);
            }
        }
    }
    
  • 相关阅读:
    Ionic Android开发环境搭建 下
    Ionic Android开发环境搭建 上
    百度地图API 简单使用
    json2.js 的使用
    第三回 Bootstrap3.x 起步
    第二回 认识CDN
    WPF 实现的等待效果界面
    AutoFac使用
    SQL语句优化
    MySQL索引的使用
  • 原文地址:https://www.cnblogs.com/wei1/p/9582068.html
Copyright © 2020-2023  润新知