Created
March 23, 2018 09:57
-
-
Save acalism/14f14bc1172425a3286de2ce2a88d465 to your computer and use it in GitHub Desktop.
同时找到最大和最小值
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 原问题:https://blog.csdn.net/harry_lyc/article/details/7715639 | |
func findMinMax<T: Comparable>(_ array: [T]) throws -> (T, T) { | |
guard array.count > 0 else { | |
throw NSError() | |
} | |
var min: T = array[0], max: T = array[0] | |
// 比较次数 O(2n) | |
// for value in array { | |
// if value < min { | |
// min = value | |
// } else if value > max { | |
// max = value | |
// } | |
// } | |
// 比较次数 O(3n/2) | |
var index = 1 | |
while index + 1 < array.count { | |
// 两两比较————每相邻的两个元素共需比较3次,而原来是每个元素比较两次 | |
let tmpMin: T | |
let tmpMax: T | |
if array[index] < array[index + 1] { | |
tmpMin = array[index] | |
tmpMax = array[index + 1] | |
} else { | |
tmpMin = array[index + 1] | |
tmpMax = array[index] | |
} | |
if min > tmpMin { | |
min = tmpMin | |
} | |
if max < tmpMax { | |
max = tmpMax | |
} | |
index += 2 | |
} | |
// 处理末尾元素 | |
if array.count % 2 == 0 { | |
let a = array.last! | |
if min > a { | |
min = a | |
} else if max < a { | |
max = a | |
} | |
} | |
return (min, max) | |
} | |
let array = [0, -1, 9, 7, 10, -2] | |
try! findMinMax(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment