iOS常见的算法面试题及(swift)答案

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..()
    for item in arr {
        dic[item] = item
    }
    print(Array(dic.keys))
}
/**  给定一个字符串,输出本字符串中只出现一次并且最靠前的那个字符的位置?如“abaccddeeef”,字符是b,输出应该是2  */
func xunzao() {
    let str = "abaccddeeef"
    var arr = Array()
    var arr1 = Array()
    for item in str.characters {
        if arr.contains(item) {
            arr1.append(item)
        }else{
            arr.append(item)
        }
    }
    var arr2 = Array()
    var arr3 = Array()
    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..

}

希望能帮到大家!

你可能感兴趣的:(文章)