56. 合并区间
题目:56. 合并区间 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
思路很清晰,对数组的操作稀烂,细节上也出现很多问题
solution
public class Solution {
public int[][] Merge(int[][] intervals) {
Array.Sort(intervals, (a,b) => a[0].CompareTo(b[0]));
List<int[]> results = new List<int[]>();
int left = intervals[0][0];
int right = intervals[0][1];
for(int i = 1; i < intervals.Length; i ++)
{
if(intervals[i][0] <= right) right = right > intervals[i][1] ? right : intervals[i][1];
else
{
results.Add(new int[]{left, right});
left = intervals[i][0];
right = intervals[i][1];
}
}
results.Add(new int[]{left, right});
return results.ToArray();
}
}
summary
错误:
1、数组操作
results应为List<int[]>
2、重叠情况
边界相同也视为重叠;
重叠时右边界扩为两个区间中较大的那个
3、最后一个数组
加入新数组的条件是发重叠区间,遍历完成时最后一个数组还没有加入
738. 单调递增的数字
题目:738. 单调递增的数字 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
思路想出来了,代码四处漏风
solution
public class Solution {
public int MonotoneIncreasingDigits(int n) {
if(n < 10) return n;
List<int> list = Transfer(n);
int start = 0;
for(int i = 1; i < list.Count; i ++)
{
if(list[i] > list[i - 1])
{
list[i] --;
start = i;
}
}
Console.WriteLine("{0}", start);
int sum = 0;
for(int i = list.Count - 1; i >= 0; i --)
{
sum = sum * 10 + (i >= start ? list[i] : 9);
Console.WriteLine("{0}", sum);
}
return sum;
}
public List<int> Transfer(int n)
{
List<int> result = new List<int>();
while(n > 0)
{
result.Add(n % 10);
n /= 10;
}
return result;
}
}
summary
错误:
1、还原整数的方法:
int sum = 0;
for(int i = list.Count - 1; i >= 0; i --)
{
sum = sum * 10 + (i >= start ? list[i] : 9);
Console.WriteLine("{0}", sum);
}
968. 监控二叉树
题目:968. 监控二叉树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
さすが困难题啊
solution
public class Solution {
public int cameraCount = 0;
public int MinCameraCover(TreeNode root) {
if(cameraTraversal(root) == 0) cameraCount ++;
return cameraCount;
}
public int cameraTraversal(TreeNode root)
{
if(root == null) return 1;
int left = cameraTraversal(root.left);
int right = cameraTraversal(root.right);
if(left == 0 || right == 0)
{
cameraCount ++;
return 2;
}
else
{
if(left == 2 || right == 2) return 1;
else return 0;
}
}
}
summary
附图总结吧。。。