Swift in place solution


  • 0
    H
    class Solution {
      func rotate(_ matrix: inout [[Int]]) {
        let d = matrix.count
        for i in 0..<Int(ceil(Double(d / 2))) {
          for j in i..<(d - i - 1) {
            let temp = matrix[i][j]
    	matrix[i][j] = matrix[d - j - 1][i]
    	matrix[d - j - 1][i] = matrix[d - i - 1][d - j - 1]
    	matrix[d - i - 1][d - j - 1] = matrix[j][d - i - 1]
    	matrix[j][d - i - 1] = temp
          }
        }
      }
    }
    

    Or even without temp var

    class Solution {
      func rotate(_ matrix: inout [[Int]]) {
        let d = matrix.count
        for i in 0..<Int(ceil(Double(d / 2))) {
          for j in i..<(d - i - 1) {
            (matrix[i][j], matrix[d - j - 1][i], matrix[d - i - 1][d - j - 1], matrix[j][d - i - 1]) = 
              (matrix[d - j - 1][i], matrix[d - i - 1][d - j - 1], matrix[j][d - i - 1], matrix[i][j])
          }
        }
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.