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

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

log con while logs findmi href exit out lex

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

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

Find the minimum element.

The array may contain duplicates.

Example 1:

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

Example 2:

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

Note:

  • This is a follow up problem to Find Minimum in Rotated Sorted Array.
  • Would allow duplicates affect the run-time complexity? How and why?

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

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

請找出其中最小的元素。

註意數組中可能存在重復的元素。

示例 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 }

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