# 0661. Image Smoother ###### tags: `Leetcode` `FaceBook` `Easy` Link: https://leetcode.com/problems/image-smoother/ ## 思路 $O(MN)$ $O(1)$ 这题不需要用PrefixSum是因为需要求和的只有9个数,跟输入长度无关 由于最大值是256,占8个bit,we can use the middle 8-bit to store the new state (average value), replace the old state with the new state by shifting all values 8 bits to the right. 0xFF是16进制里的11111111 a |= b是a = a||b a &= b是a = a&b ## Code ```java= class Solution { int[][] directions = new int[][]{{1,-1},{1,0},{1,1},{0,-1},{0,0},{0,1},{-1,-1},{-1,0},{-1,1}}; public int[][] imageSmoother(int[][] img) { for(int i = 0;i < img.length;i++){ for(int j = 0;j < img[0].length;j++){ int sum = 0; int count = 0; for(int k = 0;k < directions.length;k++){ int newi = i+directions[k][0]; int newj = j+directions[k][1]; if(newi>=0 && newi<img.length && newj>=0 && newj<img[0].length){ sum += img[newi][newj] & 0xFF; count++; } } img[i][j] |= (sum/count)<<8; } } for(int i = 0;i < img.length;i++){ for(int j = 0;j < img[0].length;j++){ img[i][j] = img[i][j]>> 8; } } return img; } } ```