在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A peak element is an element that is greater than its neighbors. Given an input array The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that Example 1: Input: nums =
Example 2: Input: nums =
Note: Your solution should be in logarithmic complexity. 峰值元素是指其值大于左右相邻值的元素。 给定一个输入数组 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 你可以假设 示例 1: 输入: nums =
示例 2: 输入: nums =
说明: 你的解法应该是 O(logN) 时间复杂度的。 32ms 1 class Solution { 2 func findPeakElement(_ nums: [Int]) -> Int { 3 var low = 0 4 var high = nums.count - 1 5 6 while low != high { 7 let mid = (low + high)/2 8 9 if !nums.indices.contains(mid - 1) { 10 if nums[mid + 1] < nums[mid] { return mid } 11 low = mid + 1 12 continue 13 } 14 15 if nums[mid - 1] < nums[mid] && nums[mid + 1] < nums[mid] { 16 return mid 17 } 18 19 if nums[mid - 1] < nums[mid] && nums[mid + 1] > nums[mid] { 20 low = mid + 1 21 continue 22 } 23 24 high = mid - 1 25 } 26 27 return high 28 } 29 } 36ms 1 class Solution { 2 func findPeakElement(_ nums: [Int]) -> Int { 3 guard nums.count > 1 else{ 4 return 0 5 } 6 var left = 0 7 var right = nums.count - 1 8 while left < right{ 9 let middle = (left + right) / 2 10 if nums[middle] > nums[middle + 1] { 11 right = middle 12 }else{ 13 left = middle + 1 14 } 15 } 16 17 return left 18 19 } 20 21 } 40ms 1 class Solution { 2 func findPeakElement(_ nums: [Int]) -> Int { 3 if nums.count >= 3 { 4 for i in Array(1..<nums.count - 1) { 5 let left = nums[i - 1] 6 let value = nums[i] 7 let right = nums[i + 1] 8 9 if value > left && value > right { 10 return i 11 } 12 } 13 } 14 15 let lower = 0 16 let upper = nums.count - 1 17 18 return nums[lower] >= nums[upper] ? lower : upper 19 } 20 } 44ms 1 class Solution { 2 func findPeakElement(_ nums: [Int]) -> Int { 3 var low = 0 4 var high = nums.count - 1 5 6 while low != high { 7 let mid = (low + high)/2 8 9 if !nums.indices.contains(mid - 1) || nums[mid - 1] < nums[mid] { 10 if nums[mid + 1] < nums[mid] { return mid } 11 low = mid + 1 12 continue 13 } 14 15 high = mid - 1 16 } 17 18 return high 19 } 20 } 52ms 1 class Solution { 2 func findPeakElement(_ nums: [Int]) -> Int { 3 var left = 0 4 var right = nums.count - 1 5 var mid = 0 6 7 while left < right { 8 mid = (right - left) / 2 + left 9 10 if nums[mid] > nums[mid + 1] { 11 right = mid 12 } else { 13 left = mid + 1 14 } 15 } 16 return left 17 } 18 }
|
请发表评论