LeetCodeSwift in LeetCode高薪算法+计算机职称考试

LeetCode 448. 找到所有数组中消失的数字 Find

2019-08-26  本文已影响0人  1江春水

【题目描述】
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

【示例】

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

【思路1】
1、将数组元素作为数组下标,将下标所对应的值置为负值,例如

Swift代码实现:

func findDisappearedNumbers(_ nums: [Int]) -> [Int] {
    if nums.isEmpty { return nums }
    var res = [Int]()
    var tmpNums = nums
    for i in 0..<tmpNums.count {
        let index = abs(tmpNums[i])-1
        tmpNums[index] = -abs(tmpNums[index])
    }
    for i in 0..<tmpNums.count {
        if tmpNums[i] >= 0 {
            res.append(i+1)
        }
    }
    return res
}

【思路2】
1、把数组元素对应为数组下标
2、每个数组值都加上数组的长度
3、然后遍历新数组,数组元素 <= 数组大小的 下标即为缺失的数字
4、时间复杂度O(n)
5、空间复杂度O(n)

Swift 代码实现:

func findDisappearedNumbers(_ nums: [Int]) -> [Int] {
    if nums.isEmpty { return nums }
    var res = [Int]()
    var tmpNums = nums
    for i in 0..<tmpNums.count {
        let index = (tmpNums[i]-1)%tmpNums.count
        tmpNums[index]+=nums.count
    }
    for i in 0..<tmpNums.count {
        if tmpNums[i] <= tmpNums.count {
            res.append(i+1)
        }
    }
    return res
}

综上所述,不太好想!

上一篇下一篇

猜你喜欢

热点阅读