8、山脉数组的峰顶索引

1、题目如下:

我们把符合下列属性的数组 A 称作山脉:

A.length >= 3
存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。

示例 1:

输入:[0,1,0]
输出:1
示例 2:

输入:[0,2,1,0]
输出:1

提示:

1、3 <= A.length <= 10000
2、0 <= A[i] <= 10^6
3、A 是如上定义的山脉

2、解题思路:

看似这道题目比较复杂,其实就是找一个数组中的最大值并返回最大值在该数组中的索引位置。

3、代码如下:

class Solution {
    public int peakIndexInMountainArray(int[] A) {
        int max=A[0],indexOfMax=0;
        for(int i=1;i<A.length;i++){
            if(max<A[i]) {
                max=A[i];
                indexOfMax=i;
            }
        }
       return indexOfMax;
    }
}

public class MainClass {
    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if (input.length() == 0) {
          return new int[0];
        }
    
        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for(int index = 0; index < parts.length; index++) {
            String part = parts[index].trim();
            output[index] = Integer.parseInt(part);
        }
        return output;
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int[] A = stringToIntegerArray(line);
            
            int ret = new Solution().peakIndexInMountainArray(A);
            
            String out = String.valueOf(ret);
            
            System.out.print(out);
        }
    }
}

4、运行结果如下:
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第四天 数组【悟空教程】 第04天 Java基础 第1章数组 1.1数组概念 软件的基本功能是处理数据,而在处理数...
    Java帮帮阅读 1,612评论 0 9
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,195评论 0 13
  • 打卡日期:2018/10/21 打卡累计天数:20/30 宣言:成为你的妈妈,是上帝对我的恩典! ✨孩子第二个30...
    何川LX阅读 137评论 0 1
  • 来尘世,赴尘缘。最深的亲人缘,最浅的察身之缘。各种各样的的缘,或深或浅,或好或坏,造就了滚滚红尘,繁华世间。善缘,...
    溪间月阅读 218评论 2 1
  • 定义和用法 sort() 方法用于对数组的元素进行排序,并返回数组。 默认排序顺序是根据字符串UniCode码。因...
    十三月_peace阅读 862评论 0 1