zoukankan      html  css  js  c++  java
  • 二分查找法

    package com.txq.test;

    public class BinarySearch {
        public int binarySearch(int []arr,int key){
            return binarySearch(arr,0,arr.length-1,key);
        }

        private int binarySearch(int[] arr, int left, int right, int key) {
            int mid = (left + right) / 2;
            if (arr[mid] == key) return mid;
            if (left <= right) {            
                if(Math.abs(arr[left] - arr[mid-1]) == (mid - 1 - left)){//左边连续
                    if((key >= arr[left] && key < arr[mid]) ||(key <= arr[left] && key > arr[mid])){
                        return binarySearch(arr,left,mid-1,key);
                    } else {
                        return binarySearch(arr,mid+1,right,key);
                    }
                } else {//右边连续
                    if((key >= arr[right] && key < arr[mid]) ||(key <= arr[right] && key > arr[mid])){
                        return binarySearch(arr,mid+1,right,key);
                    } else {
                        return binarySearch(arr,left,mid-1,key);
                    }                
                }            
            }
            return -1;        
        }
    }

  • 相关阅读:
    温故而知新 js 点击空白处关闭气泡
    javascript 打印错误信息 catch err
    ajax application/json 的坑
    nodejs 的好基友:pm2
    有道翻译 / 百度翻译Api
    PHP 正则表达式
    php 正则替换
    github get 请求指定页面的代码
    H5 input 聚焦 置顶
    autoHotKey 一些脚本积累
  • 原文地址:https://www.cnblogs.com/txq157/p/6359083.html
Copyright © 2011-2022 走看看