基础算法求目标值ampampamp字符串反转
第1题
给出一个整型数组和一个目标值,判断数组中是否有2个数之和等于目标值,若有就返回true,否则返回false。
解法:方案一:如果2层for循环暴力解题,O(n*n)不是我们想要的解法
方案二:采用集合可以优化时间复杂度,即在遍历数组的过程中,用集合每次保存当前的值。假如集合中已经有了一个数等于目标值减去当前值,则证明在之前的遍历中一定有一个数与当前值之和等于目标值。这种方法的时间复杂度是O(n). func twosums(target: Int, nums: [Int]) -> Bool { var set = Set() for num in nums { if set.contains(target - num) { return true } set.insert(num)// 如果没找到,遍历数组的过程中,用集合每次保存当前的值 } return false }
第2题:【稍微变型下】
给定一个整型数组中有且仅有俩个数之和等于目标值,求这两个数在数组中的序号。
解法:解题思路与上道题类似,但是为了得到序号,这里就使用字典。并且key是num,value是下标 func twosumsForIndex(target: Int, nums: [Int]) -> [Int] { var dict = [Int:Int]() for ( i, num ) in nums.enumerated() { if let lastIndex = dict[target - num] { return [ i, lastIndex ] }else { dict[num] = i //key是num,value是下标 } } return [] }
第3题:
给出一个字符串,要求按照单词顺序进行反转
解法:
eg: 字符串"the sky is blue",反转后的结果是"blue is sky the"
这个题想想就能感受到,不好动手呀。但是有一个很巧妙的办法:
先反转整个字符串,"the sky is blue"变成 "eulb si yks eht" 每个单词在独立反转,"eulb si yks eht"变成 "blue is sky the"
代码如下:
2个辅助函数: // 辅助函数:作用是反转 func reverse( chars: inout [T], start: Int, end: Int) { var start = start, end = end while start < end { swap(chars: &chars, p: start, q: end) start += 1 end -= 1 } } func swap(chars: inout [T], p: Int, q: Int) { (chars[p], chars[q]) = (chars[q], chars[p]) }
下面是主要的算法:func reverseWords(s: String?) -> String? { guard let s = s else { return nil } var chars = Array(s) var start = 0 , end = s.count - 1 reverse(chars: &chars, start: start, end: end) /** * 如果 chars[i+1] == " " ,说明是一个单词到了可以进行反转了 ,这里的 i+1很巧妙,后续的 i+2 也是因此而来 */ for i in 0..