|
2 | 2 |
|
3 | 3 | public class MountainArray { |
4 | 4 | public static void main(String[] args) { |
| 5 | + //[1,2,3,1] |
| 6 | + //[1,2,1,3,5,6,4] |
| 7 | + int[] array = {1,2,3,6,5,4,3,2,1}; |
| 8 | +// int[] array = {1,2,1,3,5,6,4}; |
| 9 | +// int[] array = {1,2,3,1};//[2,1] |
| 10 | +// [6,5,4,3,2,3,2] |
| 11 | +// int[] array = {6,5,4,3,2,3,2}; |
| 12 | + System.out.println("Peak Index Value is " + findPeakIndexFromArray(array)); |
| 13 | + System.out.println("Peak Number is " + array[findPeakIndexFromArray(array)]); |
| 14 | + } |
| 15 | + |
| 16 | + static int findPeakIndexFromArray(int[] nums){ |
| 17 | + |
| 18 | + int peakIndex = -1; |
| 19 | + |
| 20 | + int startIndex = 0; |
| 21 | + int endIndex = nums.length -1; |
5 | 22 |
|
| 23 | + while (startIndex <= endIndex){ |
| 24 | + //Find Middle Element |
| 25 | + int middle = startIndex + (endIndex - startIndex)/2; |
| 26 | + System.out.println("Middle Value is " + middle); |
| 27 | + |
| 28 | + if (nums.length == 1){ |
| 29 | + return nums[0]; |
| 30 | + }else if (nums.length == 2){ |
| 31 | + if (nums[0] < nums[1]){ |
| 32 | + return 1; |
| 33 | + }else { |
| 34 | + return 0; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (nums[middle] > nums[middle-1] && nums[middle] > nums[middle +1]){ |
| 39 | + System.out.println("Returning Middle Index in if condition is " + middle); |
| 40 | + return middle; |
| 41 | + } |
| 42 | + else if (nums[middle] > nums[middle+1]){ |
| 43 | + endIndex = middle; |
| 44 | + System.out.println("End Index Changed to " + middle); |
| 45 | +// System.out.println("Start Index Incremented"); |
| 46 | + }else if(nums[middle] < nums[middle+1]){ |
| 47 | + startIndex = middle; |
| 48 | + System.out.println("Start Index Changed to " + middle); |
| 49 | +// System.out.println("End Index Decremented"); |
| 50 | + }else {//if (nums[middle] > nums[middle+1] && nums[middle] < nums[middle-1]) |
| 51 | + System.out.println("Returning Middle Index in else condition is " + middle); |
| 52 | + return middle; |
| 53 | + } |
| 54 | + } |
| 55 | + return peakIndex; |
6 | 56 | } |
| 57 | + |
7 | 58 | } |
0 commit comments