博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[8.3] Magic Index
阅读量:5293 次
发布时间:2019-06-14

本文共 2044 字,大约阅读时间需要 6 分钟。

A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.

FOLLOW UP

What if the values are not distinct?

public int getMagicIndex(int[] inputs) {        return helper(0, inputs.length - 1, inputs);    }    private int helper(int start, int end, int[] inputs) {        if(end < start)             return -1;        int mid = (end - start) / 2 + start;        if(mid == inputs[mid]) {            return mid;        } else if (mid > inputs[mid]) {            return helper(mid + 1, end, inputs);        } else {            return helper(start, mid - 1, inputs);        }    }

Follow Up: 看答案的

/**     *      * A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i.      * Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.     *      * FOLLOW UP     * What if the values are not distinct?     *      */    public static void main(String[] args) {        // TODO Auto-generated method stub        int[] inputs = {-11, -9, -3, -3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 16};        System.out.println(getMagicIndex(inputs));    }    public static int getMagicIndex(int[] inputs) {        return helper(0, inputs.length - 1, inputs);    }    private static int helper(int start, int end, int[] inputs) {        if(end < start)             return -1;        int midIndex = (end - start) / 2 + start;        int midValue = inputs[midIndex];                if(midIndex == midValue) {            return midIndex;        } else {            // Search left            int leftIndex = Math.min(midIndex - 1, midValue);            int left = helper(start, leftIndex, inputs);            if(left > 0) {                return left;            }            // Search right            int rightIndex = Math.max(midIndex + 1, midValue);            return helper(rightIndex, end, inputs);        }    }

 

转载于:https://www.cnblogs.com/Phoebe815/p/6144446.html

你可能感兴趣的文章
AngularJS中transclude用法详解
查看>>
Sliding Menu Demos 浅析:Sliding Title Bar 与 Sliding Content Only
查看>>
java利用freemarker导出world
查看>>
简单的弹出拖拽窗口(二)
查看>>
LeetCode题解之 Assign Cookies
查看>>
第八周编程总结
查看>>
Java-----思想认识
查看>>
ASP.NET - TreeView控件,只操作最后一级节点
查看>>
设计模式示例系列随笔
查看>>
HTTP协议概述
查看>>
Available to Promise (ATP) in SAP-SD
查看>>
Google Talk
查看>>
Spring 之注解事务 @Transactional
查看>>
ArrayList,LinkedList的对比
查看>>
eclipse 最简单的方法 显示行号
查看>>
Winform应用ssk皮肤
查看>>
Java实现二叉树先序,中序,后序遍历
查看>>
Hello World
查看>>
java 打印栈信息
查看>>
解决flex4 分辨率自适应问题
查看>>