leetcode 记录
Posted 保护眼睛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 记录相关的知识,希望对你有一定的参考价值。
19.删除链表的倒数第n个节点
只遍历一遍链表
class Solution19 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode slow = head;
ListNode fast = head;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
if (fast == null) {
return head.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
1108.IP地址无效化
class Solution1108 {
public static String defangIPaddr1(String address) {
return address.replace(".", "[.]");
}
public String defangIPaddr2(String address) {
StringBuilder res = new StringBuilder();
int len = address.length();
for (int i = 0; i < len; i++) {
char ch = address.charAt(i);
if (ch == '.') {
res.append("[.]");
} else {
res.append(ch);
}
}
return res.toString();
}
}
575.分糖果
class Solution575 {
class Solution {
public int distributeCandies(int[] candyType) {
HashSet<Integer> set = new HashSet<>();
for (int i : candyType) {
set.add(i);
}
return Math.min(set.size(), candyType.length / 2);
}
}
}
1103.分糖果II
class Solution1103 {
public static void main(String[] args) {
System.out.println(Arrays.toString(distributeCandies(7, 4)));
}
public static int[] distributeCandies(int candies, int num_people) {
int[] res = new int[num_people];
int getCandies = 1;
while (candies > 0) {
for (int i = 0; i < num_people; i++) {
if (candies - getCandies > 0) {
candies -= getCandies;
res[i] += (getCandies++);
} else {
res[i] += candies;
return res;
}
}
}
return res;
}
}
手套问题
class SolutionSolves {
public int findMinimum(int n, int[] left, int[] right) {
int sum_left = 0;
int sum_right = 0;
int left_min = Integer.MAX_VALUE;
int right_min = Integer.MAX_VALUE;
int zero_color = 0;
for (int i = 0; i < n; i++) {
if (left[i] * right[i] == 0) {
zero_color += left[i];
zero_color += right[i];
} else {
left_min = Math.min(left_min, left[i]);
right_min = Math.min(right_min, right[i]);
sum_left += left[i];
sum_right += right[i];
}
}
return (sum_left < sum_right ? sum_left - left_min + zero_color + 2
: sum_right - right_min + zero_color + 2);
}
}
559.求N叉树的深度
class Solution559 {
//递归实现
public int maxDepth(Node root) {
if (root == null) return 0;
int res = 1;
for (Node child : root.children) {
res = Math.max(res, maxDepth(child) + 1);
}
return res;
}
//非递归实现
public int maxDepth1(Node root) {
if (root == null) return 0;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
depth++;
int size = queue.size();
for (int i = 0; i < size; i++) {
Node cur = queue.poll();
for (Node child : cur.children) {
queue.offer(child);
}
}
}
return depth;
}
}
以上是关于leetcode 记录的主要内容,如果未能解决你的问题,请参考以下文章
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段
错误记录Flutter 混合开发获取 BinaryMessenger 报错 ( FlutterActivityAndFragmentDelegate.getFlutterEngine() )(代码片段