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

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

arr become som The tar ted unknown 最小值 you

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.

You may assume no duplicate exists in the array.

Example 1:

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

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

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

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

請找出其中最小的元素。

你可以假設數組中不存在重復元素。

示例 1:

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

示例 2:

輸入: [4,5,6,7,0,1,2]
輸出: 0

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

16ms

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

24ms

 1 class Solution {
 2     
 3     func findMin(_ nums: [Int]) -> Int {
 4         var start = 0
 5         var end = nums.count - 1
 6         
 7         while start < end {
 8             if nums[start] < nums[end] {
 9                 return nums[start]
10             }
11             
12             var mid = (start + end) / 2
13             
14             if nums[mid] >= nums[start] {
15                 start = mid + 1
16             }else {
17                 end = mid
18             }
19         }
20         
21         return nums[start]
22     }
23     
24     func findMin2(_ nums: [Int]) -> Int {
25         for i in 1 ..< nums.count {
26             if nums[i] < nums [i-1]{
27                 return nums[i]
28             }
29         }
30         
31         return nums[0]
32     }
33 }

28ms

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

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