• + 0 comments

    swift

    func absolutePermutation(n: Int, k: Int) -> [Int] {
        var results: [Int] = [Int]()
        var isUpper: Bool = false
        
        if k == 0 { return Array(1 ... n) }
        
        for number in 0 ... n - 1 {        
            if number % k == 0 { isUpper = !isUpper }
            
            if isUpper { results.append((number + 1) + k) }
            else { results.append((number + 1) - k) }
        
            if results.last! > n { return [-1] }
        }
        return results
    }