zoukankan      html  css  js  c++  java
  • Maximum element in a sorted and rotated array排序和旋转数组中的最大元素

    参考:https://www.geeksforgeeks.org/maximum-element-in-a-sorted-and-rotated-array/

    给定在某个未知点旋转的不同元素的排序数组arr[],任务是找到其中的最大元素。
    例子:

    输入: arr[] = {3, 4, 5, 1, 2}
    输出: 5
    输入: arr[] = {1, 2, 3}
    输出: 3

    思路:

    如果最大元素不在中间(既不是 mid 也不是 mid + 1),则最大元素位于左半边或右半边。
    如果中间元素大于最后一个元素(已经反了),则最大元素位于左半部分。
    否则最大元素位于右半部分。

    // Java implementation of the approach
    class GFG
    {
        
    // Function to return the maximum element
    static int findMax(int arr[], int low, int high)
    {
    
        // This condition is for the case when
        // array is not rotated at all
        if (high < low)
            return arr[0];
    
        // If there is only one element left
        if (high == low)
            return arr[low];
    
        // Find mid
        int mid = low + (high - low) / 2;
    
        // Check if mid itself is maximum element
        if (mid < high && arr[mid + 1] < arr[mid])
        {
            return arr[mid];
        }
    
        // Check if element at (mid - 1) is maximum element
        // Consider the cases like {4, 5, 1, 2, 3}
        if (mid > low && arr[mid] < arr[mid - 1])
        {
            return arr[mid - 1];
        }
    
        // Decide whether we need to go to
        // the left half or the right half
        if (arr[low] > arr[mid])
        {
            return findMax(arr, low, mid - 1);
        }
        else
        {
            return findMax(arr, mid + 1, high);
        }
    }
    
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 5, 6, 1, 2, 3, 4 };
        int n = arr.length;
        System.out.println(findMax(arr, 0, n - 1));
    }
    }
    
    // This code is contributed by Code_Mech.
    View Code
     
  • 相关阅读:
    code#5 P2 棋子
    code#5 P1 报告
    ztz11的noip模拟赛T3:评分系统
    20181101noip模拟赛T1
    20181031noip模拟赛T2
    20181031noip模拟赛T1
    Linux进程的五个段
    进程和线程有什么区别
    shell中if条件字符串、数字比对,[[ ]]和[ ]区别
    Python实现单例模式
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14843389.html
Copyright © 2011-2022 走看看