Skip to content

Commit 81c5880

Browse files
committed
update leetcode
1 parent 15175b5 commit 81c5880

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

leetcode/IslandPerimeter.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class Solution {
2+
private static final int[] dir_x = {0, 0, 1, -1};
3+
private static final int[] dir_y = {1, -1, 0, 0};
4+
5+
public int islandPerimeter(int[][] grid) {
6+
int res = 0;
7+
for (int i = 0; i < grid.length; ++i) {
8+
for (int j = 0; j < grid[i].length; ++j) {
9+
if (grid[i][j] != 1) {
10+
continue;
11+
}
12+
for (int k = 0; k < 4; ++k) {
13+
int nx = dir_x[k] + i;
14+
int ny = dir_y[k] + j;
15+
if (nx < 0 || nx >= grid.length || ny < 0 || ny >= grid[i].length || grid[nx][ny] == 0) {
16+
++res;
17+
}
18+
}
19+
}
20+
}
21+
return res;
22+
}
23+
24+
public static void main(String[] args) {
25+
Solution solution = new Solution();
26+
int[][] grid = new int[][]{
27+
{0,1,0,0},
28+
{1,1,1,0},
29+
{0,1,0,0},
30+
{1,1,0,0}
31+
};
32+
System.out.println(solution.islandPerimeter(grid));
33+
}
34+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
public:
6+
int minMoves2(vector<int>& nums) {
7+
if (nums.empty()) {
8+
return 0;
9+
}
10+
sort(nums.begin(), nums.end());
11+
int median = nums[(int)nums.size() / 2];
12+
int res = 0;
13+
for (int i = 0; i < (int)nums.size(); ++i) {
14+
res += abs(median - nums[i]);
15+
}
16+
return res;
17+
}
18+
};
19+
20+
int main() {
21+
Solution solution;
22+
vector<int> nums = {1, 2, 3};
23+
cout << solution.minMoves2(nums) << endl;
24+
return 0;
25+
}

0 commit comments

Comments
 (0)