import Foundation
// unique 去重不排序,unique_sorted 去重排序
extension Sequence where Element: Hashable,Element:Comparable {
func unique() -> [Element] {
var seen: Set<Element> = []
return filter { seen.insert($0).inserted }
}
func unique_sorted() -> [Element] {
var seen: Set<Element> = []
let arr = filter { seen.insert($0).inserted }
return arr.sorted()
}
}
let re = [10,2,5,2]
print(re.unique()) //[10, 2, 5]
print(re.unique_sorted()) //[2, 5, 10]
import Foundation
extension Sequence where Element: Hashable,Element:Comparable {
func unique_sorted() -> [Element] {
var seen: Set<Element> = []
let arr = filter { seen.insert($0).inserted }
return arr.sorted()
}
}
extension Array where Element: Hashable,Element:Comparable {
func findKthMax(_ k:Int) -> Element? {
self.unique_sorted()[k]
}
func binarySearch(_ key: Element) -> Int? {
let a = self
var lowerBound = 0
var upperBound = a.count
while lowerBound < upperBound {
let midIndex = lowerBound + (upperBound - lowerBound) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
lowerBound = midIndex + 1
} else {
upperBound = midIndex
}
}
return nil
}
}
print(re.findKthMax(2)!) //10
print("binarySearch:",[1,2,5].binarySearch(5)!) //2
func maximumProduct(nums:[Int]) -> Int {
let nums = nums.sorted()
let len = nums.count
let t:Int = max(nums[0]*nums[1]*nums[len-1],nums[len-1]*nums[len-2]*nums[len-3])
return t
}
print("\(maximumProduct(nums:[1,2,3,4]))") //24
public func bubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
var array = elements
var swapped = true
while swapped {
swapped = false
for i in 1..<array.count {
if array[i - 1] > array[i] {
let tmp = array[i-1]
array[i-1] = array[i]
array[i] = tmp
swapped = true
}
}
}
return array
}
print("\(bubbleSort([10,15,1]))")//[1, 10, 15]
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
var sortedArray = array
for var index in 1..<sortedArray.count {
let temp = sortedArray[index]
while index > 0, temp < sortedArray[index - 1] {
sortedArray[index] = sortedArray[index - 1]
index -= 1
}
sortedArray[index] = temp
}
return sortedArray
}
print("\(insertionSort([10,15,1]))")//[1, 10, 15]
extension Array where Element: Hashable,Element:Comparable,Element:Numeric {
func sum() -> Element {
var res:Element = 0
for val in self {
res = res+val
}
return res
}
func min_val() -> Element? {
self.min()
}
func max_val() -> Element? {
self.max()
}
func len() -> Int{
self.count
}
}
func minMoves(_ nums:[Int])->Int{
nums.sum()-(nums.min()!*nums.len())
}
print("\(minMoves([1,2,3]))")//3