使用 LeetCode 832 進行練習 :
https://leetcode.com/problems/flipping-an-image/
Given a binary matrix A
, we want to flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0]
horizontally results in [0, 1, 1]
.
To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
. For example, inverting [0, 1, 1]
results in [1, 0, 0]
.
Example 1:
Input: [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
沒有想到比較好的寫法
使用 for 迴圈 :
int[][] A = new int[][] { new int[]{1, 1, 0}, new int[]{1, 0, 1}, new int[]{0, 0, 0} }; Solution solution = new Solution(); var actual = solution.FlipAndInvertImage(A); var expected = new int[][] { new int[]{1, 0, 0}, new int[]{0, 1, 0}, new int[]{1, 1, 1} }; for (int i = 0; i < actual.Length; i++) { CollectionAssert.AreEqual(expected[i], actual[i]); }
使用 IEqualityComparer
[TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { int[][] A = new int[][] { new int[]{1, 1, 0}, new int[]{1, 0, 1}, new int[]{0, 0, 0} }; Solution solution = new Solution(); var actual = solution.FlipAndInvertImage(A); var expected = new int[][] { new int[]{1, 0, 0}, new int[]{0, 1, 0}, new int[]{1, 1, 1} }; for (int i = 0; i < actual.Length; i++) { CollectionAssert.AreEqual(expected[i], actual[i]); } Assert.IsTrue(expected.SequenceEqual(actual,new MyCustomCheck())); } internal class MyCustomCheck : IEqualityComparer<int[]> { public bool Equals(int[] x, int[] y) { return x.SequenceEqual(y); } public int GetHashCode(int[] obj) { return obj.GetHashCode(); } } }