本文主要是介绍JAVA代码—算法基础:寻找一维整型数组中的 Peak Element,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
寻找一维整型数组中的 Peak Element
题目描述:在一个一维整型数组中,所谓的 Peak Element就是该元素比它的相邻的元素都大。
假设 给定一个一维数组,其元素满足关系:num[i] ≠ num[i+1],查找 Peak Element 元素,并且返回该元素的下标。
如果这个一维数组中包含多个 Peak Element,返回其中任何一个Peak Element元素的下标即可。
算法设计
package com.bean.algorithmbasic;public class FindPeakElement {public static void main(String[] args) {// TODO Auto-generated method stub/** A peak element is an element that is greater than its neighbors. * Given an input array where num[i] ≠ num[i+1], * find a peak element and return its index. * The array may contain multiple peaks, in that case return * the index to any one of the peaks is fine.* You may imagine that num[-1] = num[n] = -∞. * For example, in array [1, 2, 3, 1], * 3 is a peak element and your function should return the index number 2.* */int[] arrayDemo= {1, 2, 3, 1};int index=findPeakElement(arrayDemo);System.out.println("INDEX = "+index);}/** 查找 Peak Element的算法*/public static int findPeakElement(int[] num) {int max = num[0];int index = 0;for(int i=1; i<=num.length-2; i++){int prev = num[i-1];int curr = num[i];int next = num[i+1];if(curr > prev && curr > next && curr > max){index = i;max = curr;}}if(num[num.length-1] > max){return num.length-1;}return index;}}
(完)
这篇关于JAVA代码—算法基础:寻找一维整型数组中的 Peak Element的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!