int findPeakElement(int* nums, int numsSize) { int left = 0, right = numsSize - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; } // Input array: [1, 3, 20, 4, 1, 0]
The function uses binary search to find a peak element index. It compares nums[mid] and nums[mid+1]. If nums[mid] is greater, the peak is on the left side including mid, so right = mid. Otherwise, the peak is on the right side excluding mid, so left = mid + 1. For the input [1, 3, 20, 4, 1, 0], the peak is at index 2 with value 20.
int findPeakElement(int* nums, int numsSize) { int left = 0, right = numsSize - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; } // Input array: [10, 20, 15, 2, 23, 90, 67]
The function finds a peak element index using binary search. For the input, there are multiple peaks: 20 at index 1 and 90 at index 5. The binary search will find index 5 because it moves towards the right peak due to comparisons.
The binary search works because if nums[mid] > nums[mid+1], then a peak must exist on the left side including mid. Otherwise, the peak is on the right side. This logic ensures the search space reduces correctly to find a peak.
int findPeakElement(int* nums, int numsSize) { int left = 0, right = numsSize - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] > nums[mid + 1]) { right = mid - 1; } else { left = mid + 1; } } return left; } // Input array: [1, 2, 3, 1]
The loop condition allows mid to be equal to right, which can be numsSize - 1. Accessing nums[mid + 1] then causes an out of bounds error.
In a circular array, neighbors wrap around. So to find a peak, compare nums[mid] with both neighbors using modulo to handle wrapping. This guides the binary search correctly.
