Sharing my 8ms C++ solution


  • 1
    T
    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            int left = 0;
            int right = nums.size()-1;
            int middle;
            while(left<right)
            {
                middle = (left+right)/2;
                if(nums[middle]>nums[middle+1])
                    right = middle;
                else
                    left = middle+1;
            }
            
            return left;
        }
    };

  • -3
    class Solution {
    public:
    	int findPeakElement(vector<int>& nums) {
    		for (size_t i = 1; i < nums.size()-1; i++)
    		{
    			if (nums[i - 1]<nums[i] && nums[i]>nums[i + 1]) 
    			{
    				return i;
    			}
    		}
    
    	}
    };
    

    我的代码为什么不对呢?想不明白,极值点不就是比周围都大吗


  • 0
    H

    可能时间复杂度不是log n吧


  • 0
    G

    nums[0]和nums[n - 1]没考虑


Log in to reply
 

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