Create 661. Image Smoother.md

This commit is contained in:
唐树森 2018-09-11 23:12:09 +08:00 committed by GitHub
parent 2b6d39616e
commit e15c8e15a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

48
661. Image Smoother.md Normal file
View File

@ -0,0 +1,48 @@
# [661. Image Smoother](https://leetcode.com/problems/image-smoother/description/)
# 思路
将二维数组遍历一遍每次按照题意计算avg值实现相邻的小trick:
```
int dx[8] = {1, -1, 1, -1, 1, 0, -1, 0};
int dy[8] = {-1, 1, 1, -1, 0, 1, 0, -1};
for(int k = 0; k < 8; k++){
new_x = x + dx[k];
new_y = y + dy[k];
}
```
另外要注意判断以上代码算出来的相邻坐标是否合法。
空间上改进:
由于元素值为0-255 所以最多8位所以可以先用int型的高8位存放新的值这样就可以使空间复杂度为O(1)。
# C++
```
class Solution {
public:
bool islegal(const int& x, const int& y, const int& r, const int &c){
if(x < 0 || y < 0 || x >= r || y >= c) return false;
return true;
}
vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
int dx[8] = {1, -1, 1, -1, 1, 0, -1, 0};
int dy[8] = {-1, 1, 1, -1, 0, 1, 0, -1};
int r = M.size(), c = M[0].size(), sum, count;
vector<vector<int>>res;
vector<int>tmp;
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
sum = M[i][j], count = 1;
for(int k = 0; k < 8; k++){
if(islegal(i + dx[k], j + dy[k], r, c)) {
sum += M[i + dx[k]][j + dy[k]];
count++;
}
}
tmp.push_back(sum / count);
}
res.push_back(tmp);
tmp.clear();
}
return res;
}
};
```