O(N) solution, Java code


  • -1
    1
    1. Traverse num
    2. In the for-loop, find if it is a extreme value:
      If it is minimal value, continue; else(it is a maximal value), return.
    3. No value was found in the for-loop,return the index of first or last element.

    Code:

    public class Solution {
    public int findPeakElement(int[] num) {
        if (num == null || num.length < 1) {
            return 0;
        } 
        
        if (num.length == 1) {
            return 0;
        }
        
        int difference = num[1] - num[0];
        
        for (int i = 1; i < num.length - 1; i++) {
            if ((difference >= 0 && num[i + 1] - num[i] >= 0) || (difference <= 0 && num[i + 1] - num[i] <= 0)) {
                difference = num[i + 1] - num[i];
                continue;
            }
            
            if (num[i] < num[i + 1])
                continue;
            else
                return i;
        }
        
        if (num[0] > num[1])
            return 0;
        return num.length - 1;
    }
    

    }


  • 0
    Y
    public class Solution {
    public int findPeakElement(int[] num) {
        int len =0;
        for(int i=0; i<num.length; i++){
            if(num[len]>=num[i]){
                continue;
            }
            if(num[len]<num[i]){
                len=i;
            }
        }
        return len;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.