import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// paixu()
// daoxu()
// shaixuan()
// xunzao()
// erfenfa()
// print(digui())
// sushu()
gongyueshu(a: 55, b: 100)
}
/** 冒泡排序 */
func paixu() {
var arr = [24,17,85,13,9,54,76,45,5,63]
for i in 0..<arr.count {
for j in 0..<arr.count - 1 - i {
if arr[j] < arr[j + 1] {
let tmp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = tmp
}
}
}
print(arr)
//sort 是對數組自身停止排序,也就是意味著 sort 辦法會修正數組自身的內容。 而 sorted 就不會修正原有的數組,而是前往一個經過排序處置後的新的數組
arr.sort {$0 < $1}
print(arr)
print(arr.sorted {$0 < $1})
}
/** 倒序輸入 */
func daoxu() {
let str = "how are you"
//先拆分紅數組
let arr = str.characters.split(separator: " ").map(String.init)
//倒序輸入
//reversed 辦法可以將數組中的元素倒序陳列
let arr1 = Array(arr.reversed())
print(arr1)
for item in arr1 {
print(item)
}
}
/** 挑選 */
func shaixuan() {
let arr = [2,3,4,5,4,3,7,8,3]
//用集合最復雜
let set = Set(arr)
let arr1 = Array(set)
print(arr1)
//字典挑選key
var dic = Dictionary<Int, Any>()
for item in arr {
dic[item] = item
}
print(Array(dic.keys))
}
/** 給定一個字符串,輸入本字符串中只呈現一次並且最靠前的那個字符的地位?如“abaccddeeef”,字符是b,輸入應該是2 */
func xunzao() {
let str = "abaccddeeef"
var arr = Array<Character>()
var arr1 = Array<Character>()
for item in str.characters {
if arr.contains(item) {
arr1.append(item)
}else{
arr.append(item)
}
}
var arr2 = Array<Character>()
var arr3 = Array<Character>()
for item in str.characters {
if !arr1.contains(item) {
arr2.append(item)
}
arr3.append(item)
}
print(arr3.index(of: arr2.first!)! + 1)
}
/** 二分法查找(只適用於有序數組) */
func erfenfa() {//36
let tmp = 36
var array = [1, 2, 50, 3, 9, 5, 5, 7, 10, 36]
//先排序
array.sort()
print(array)
var left = 0
var right = (array.count - 1)
while left <= right {
let mid = (left + right) / 2
let value = array[mid]
if value == tmp {
return
}
if value < tmp {
left = mid + 1
}
if value > tmp {
right = mid - 1
}
}
}
/** 遞歸法查找 */
var left = 0
func digui() -> Int {
let tmp = 36
var array = [1, 2, 50, 3, 9, 5, 5, 7, 10, 36]
let right = (array.count - 1)
var mid = (left + right) / 2
let value = array[mid]
if left > right {
return -1
}else{
left += 1
if value == tmp {
return mid
}else if value > tmp {
mid = mid - 1
return self.digui()
}else{
mid = mid + 1
return self.digui()
}
}
}
/** 2-100之間的素數 */
func sushu() {
for i in 2..<100 {
var r : Int = 1
for j in 2..<i {
if i%j == 0 {
r = 0
break
}
}
if r == 1 {
print(i)
}
}
}
/** 兩個整數的最大條約數 */
func gongyueshu( a:Int, b:Int) {
var a = a
var b = b
var tmp = 0
if a < b {
tmp = a
a = b
b = tmp
}
while b != 0 {
tmp = a%b
a = b
b = tmp
}
print(a)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
希望能幫到大家!
【iOS罕見的算法面試題及(swift)答案】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!