[Swift]LeetCode154. 尋找旋轉排序數組中的最小值 II | Find Minimum in Rotated Sorted Array II

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-ymcujxjj-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.git

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).github

Find the minimum element.算法

The array may contain duplicates.數組

Example 1:微信

Input: [1,3,5]
Output: 1

Example 2:spa

Input: [2,2,2,0,1]
Output: 0

Note:code


假設按照升序排序的數組在預先未知的某個點上進行了旋轉。htm

( 例如,數組 [0,1,2,4,5,6,7] 可能變爲 [4,5,6,7,0,1,2] )。blog

請找出其中最小的元素。

注意數組中可能存在重複的元素。

示例 1:

輸入: [1,3,5]
輸出: 1

示例 2:

輸入: [2,2,2,0,1]
輸出: 0

說明:


 

16ms

 1 class Solution {
 2     func findMin(_ nums: [Int]) -> Int {
 3         var left = 0 
 4         var right = nums.count - 1
 5         while left < right {
 6             if nums[left] < nums[right] { return nums[left] }
 7             let mid = (left + right) / 2
 8             if nums[mid] < nums[left] {
 9                 right = mid
10             } else if nums[mid] > nums[right] {
11                 left = mid + 1
12             } else {
13                 right -= 1
14             }
15         }
16         return nums[left]
17     }
18 }

52ms

 1 class Solution {
 2     func findMin(_ nums: [Int]) -> Int {
 3         let arraySize = nums.count
 4 
 5         if arraySize == 1 { return nums[0] }
 6         if arraySize == 2 { return min(nums[0], nums[1]) }
 7         let midElement = arraySize / 2
 8         if nums[midElement] > nums[arraySize-1] {
 9             return findMin(Array(nums[midElement...arraySize-1]))
10         } else if nums[midElement] < nums[0] {
11             return findMin(Array(nums[0...midElement]))
12         } else {
13             return min(findMin(Array(nums[midElement...arraySize-1])), findMin(Array(nums[0...midElement])))
14         }
15     }
16 }

60ms

 1 class Solution {
 2     func findMin(_ nums: [Int]) -> Int {
 3 
 4         if nums.isEmpty {
 5             return -1
 6         }
 7 
 8         if nums.count == 1 {
 9             return nums[0]
10         }
11         
12         var beigin = nums[0]
13         var i = 1
14         while i < nums.count {
15             if nums[i] >= beigin {
16                 beigin = nums[i]
17                 i += 1
18             } else {
19                 return nums[i]
20             }
21         }
22 
23         return nums[0]
24     }
25 }

76ms

1 class Solution {
2     func findMin(_ nums: [Int]) -> Int {
3         guard nums.count > 0 else { return -1 }
4         return nums.min()!
5     }
6 }
相關文章
相關標籤/搜索