今天想起年前有一道题没有一次通过,记录一下
求一个只包含0和1的二维数组中,由包含连续1(上下左右连续)最多的图形中,1的个数
//因为这个数组中可能有多块这种图形,所以先求一块图形的面积,再在所有图形中选出包含最多1的图形
int OneArea(int row, int col, int[,] grid, bool[,] visited)
{
if(row < 0 || row >= grid.GetLength(0) || col < 0 || col > grid.GetLength(1) || grid[row, col] = 0 || visited[row, col] == true)
{
return 0;
}
visited[row, col] = true;
return ( 1+OneArea(row-1, col, grid, visited)+OneArea(row+1, col, grid, visited)+OneArea(row, col-1, grid, visited)+OneArea(row, col+1, grid, visited));
}
int MaxArea(int[,] grid)
{
bool[,] visited = new bool[grid.GetLength(0), grid.GetLength(1)];
int maxArea = 0;
for(int row = 0; row < grid.GetLength(0); row++)
{
for(int col = 0; col < grid.GetLength(1); col++)
{
maxArea = Math.Max(maxArea, OneArea(row, col, grid, visited);
}
}
return maxArea;
}
再记一道刚做的题,自己的解法速度慢,主要记一下效率更高的别人的做法
将一个一维正整数数组中的所有0移到数组的最后,要求保持其它非0数字原有的顺序,且不能使用复制数组的方法
我自己效率低的做法:
void MoveZero(int[] nums)
{
int i = 0;
int zero = 0;
int nonZero = 0;
while(iif(nums[i] == 0)
{
int j = i;
while(j < nums.Length-1)
{
nums[j] = nums[j+1];
j++;
}
nums[nums.Length-1] = 0;
}
else
{
i++;
}
}
}
别人的高效率版本:
void MoveZero(int[] nums)
{
int index = 0;
for(int i = 0; i < nums.Length; i++)
{
if(nums[i] != 0)
{
nums[index++] = nums[i];
}
}
while(index < nums.Length - 1)
{
nums[index++] = 0;
}
}
Q3:
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
List<int> FindDispearNum(int[] nums)
{
List<int> result = new List<int>();
for(int i = 0; i < nums.Length; i++)
{
int tmp = nums.Length - Math.Abs(nums[i]);
if(nums[tmp] > 0)
{
nums[tmp] = -nums[tmp];
}
}
for(int i = nums.Length - 1; i >= 0; i--)
{
if(nums[i] > 0)
{
result.Add(nums.Length - i);
}
}
return result;
}