Java 2 lines trick solution


  • 0
    Z

    My idea is borrowed from question Next Permutation, all I do is walking through the array starting from end to start to find the first element of the decreasing sub-sequence.
    Two special cases: 1) Only one element, just return 0. 2) Entire array is decreasing or flat ( all elements have the same value) my code will also return 0;

    Just note that, my solution runs in worst case O(n) time complexity.

    public int findPeakElement(int[] nums) {
            for(int i = nums.length - 1; i > 0; i--) if(nums[i-1] < nums[i]) return i;
            return 0;
    }
    

Log in to reply
 

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