Swift solution - Binary Search, recursive


  • 0
    class Solution {
        func findPeakElement(_ nums: [Int]) -> Int {
            if nums.count == 0 {
                return 0
            }
            
            var left = 0
            var right = nums.count - 1
            var middle1 = 0
            var middle2 = 0
            
            while left < right {
                middle1 = (left + right) / 2
                middle2 = middle1 + 1
                if nums[middle1] < nums[middle2] {
                    left = middle2
                } else {
                    right = middle1
                }
            }
            
            return left
        }
        
        func findPeakElement_Recursive(_ nums: [Int]) -> Int {
            if nums.count == 0 {
                return 0
            }
            
            return helper(nums, 0, nums.count - 1)
        }
        
        private func helper(_ nums: [Int], _ left: Int, _ right: Int) -> Int {
            if left == right {
                return left
            } else {
                let middle1 = (left + right) / 2
                let middle2 = middle1 + 1
                if nums[middle1] > nums[middle2] {
                    return helper(nums, left, middle1)
                } else {
                    return helper(nums, middle2, right)
                }
            }
        }
    }
    

Log in to reply
 

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