Leetcode Note: Go - Flipping an Image

Flipping an Image - LeetCode
https://leetcode.com/problems/flipping-an-image/

  • Go 言語で取り組んだメモ

所感

  • image matrix が int[][] で渡されるので値をを flip して int[][] で return する

回答

Flipping an Image - LeetCode
https://leetcode.com/problems/flipping-an-image/solution/

One pass with Go - LeetCode Discuss
https://leetcode.com/problems/flipping-an-image/discuss/2469608/One-pass-with-Go

func flipAndInvertImage(image [][]int) [][]int {
    flip := func(a int) int {
        if a == 0 {
            return 1
        }
        
        return 0
    }
    
    for row := 0; row < len(image); row++ {
        l, r := 0, len(image[row])-1
        
        for l < r {
            image[row][l], image[row][r] = flip(image[row][r]), flip(image[row][l])
            l++
            r--
        }
        
        if l == r {
            image[row][r] = flip(image[row][r])
        }
    }
    
    return image
}