Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

翻转图像 #116

Open
yankewei opened this issue Feb 24, 2021 · 1 comment
Open

翻转图像 #116

yankewei opened this issue Feb 24, 2021 · 1 comment
Labels
数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。

水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。

反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。

示例 1:

输入:[[1,1,0],[1,0,1],[0,0,0]]
输出:[[1,0,0],[0,1,0],[1,1,1]]
解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
     然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]

示例 2:

输入:[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
     然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

提示:

  • 1 <= A.length = A[0].length <= 20
  • 0 <= A[i][j] <= 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flipping-an-image
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 数组 题目类型为数组 简单 题目难度为简单 labels Feb 24, 2021
@yankewei
Copy link
Owner Author

模拟 + 双指针优化

一个数组的首尾交换可以用双指针来进行交换,但是由于题目中说了,为0或者1,所以如果首尾两个指针的值不一样,翻转后再反转其实没有变化,所以如果两个指针的值不同,不进行任何操作,如果相同,直接取反即可,省去了交换的步骤。

func flipAndInvertImage(A [][]int) [][]int {
    for i := 0; i< len(A); i++ {
        left, right := 0, len(A[i])-1 
        for left < right {
            if A[i][left] == A[i][right] {
                A[i][left] ^= 1
                A[i][right] ^= 1
            }
            left++
            right--
        }
        // 可能left和right相同
        if left == right {
            A[i][left] ^= 1
        }
    return A
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant