• 1095. 山脉数组中查找目标值


    在这里插入图片描述
    在这里插入图片描述

    二分查找

    • 使用二分查找查找山脉数组的峰值位置
    • 将数组以峰值位置为分界线分为左右两部分,并分别使用二分查找查询目标值

    二分查找就是每次查找将范围缩小一半

    /**
     * // This is MountainArray's API interface.
     * // You should not implement it, or speculate about its implementation
     * interface MountainArray {
     *     public int get(int index) {}
     *     public int length() {}
     * }
     */
     
    class Solution {
        public int findInMountainArray(int target, MountainArray mountainArr) {
            int n = mountainArr.length();
            int left = 0, right = n-1;
            while (left < right) {
                int mid = (left + right) / 2;
                if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
                    left = mid + 1;
                } else {
                    right = mid;
                }
            } 
            int peek = left;
            int index = binarySearch(target, mountainArr, 0, peek, true);
            if (index != -1) {
                return index;
            }
            return binarySearch(target, mountainArr, peek + 1, n - 1, false);
        }
    
        // flag true:递增 false: 递减
        private int binarySearch(int target, MountainArray mountainArr, int left, int right, boolean flag) {
            if (!flag) {
                target *= -1;
            }
            while (left <= right) {
                int mid = (left + right) / 2;
                int cur = mountainArr.get(mid) * (flag ? 1 : -1);
                if (cur > target) {
                    right = mid - 1;
                } else if (cur < target) {
                    left = mid + 1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
    }
    
  • 相关阅读:
    vue-router路由知识补充
    vue-router路由模式详解
    Linq To Sql的各种查询
    消息队列系列(四):Rabbitmq常用命令行
    产品发布之我见
    利用LogParser分析IIS日志
    SqlServer_删除重复行只保留一条记录
    SqlServer_合并多个递归查询数据(CTE)
    rabbitmq_坑
    mongodb_性能监控
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859904.html
Copyright © 2020-2023  润新知