https://leetcode.com/problems/sort-list/
题意
不借助额外空间对链表进行排序解法
先使用快慢指针将链表分为前后两部分,分别对两部分排序,最后对排序好的两个链表进行合并
class Solution {
public ListNode sortList(ListNode head) {
//当head为null或仅剩head的时候直接返回
if (head == null || head.next == null) {
return head;
}
ListNode fast =...
https://leetcode.com/problems/insertion-sort-list/
题意
使用插入排序对链表进行排序笨办法
每次找错序的节点,断开该节点后从头开始查找合适位置并插入,能AC但是非常慢class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
//是否查找到最...
https://leetcode.com/problems/binary-tree-postorder-traversal/
题意
后序遍历树,非递归实现,基本跟144一致,只是最后结果需要reverse一下,但是速度比较慢
class Solution {
List<Integer> results = new ArrayList<>();
Stack<TreeNode> stacks = new Stack<>();
public List<Integer> postorderTraversal(TreeNod...
https://leetcode.com/problems/binary-tree-preorder-traversal/
题意
二叉树前序遍历,递归的比较简单,非递归实现需要用栈存节点
class Solution {
List<Integer> results = new ArrayList<>();
Stack<TreeNode> stacks = new Stack<>();
public List<Integer> preorderTraversal(TreeNode root) {
if (...
题意
https://leetcode.com/problems/reorder-list/
给链表重新排序,顺序变为L0→Ln→L1→Ln-1→L2→Ln-2→…笨办法
每次找到最后一个节点,并断开最后一个节点与上一个节点连接,使第一个节点指向最后一个节点,最后一个节点指向第一个节点的原next节点。虽然能AC但是极慢
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
...
题意
给一个字符串和一个字符串数组,判断字符串是否能由数组的字符串组合而成,可以重复使用同时不必全部使用,并输出所有解思路
一开始想着跟上一题一样的解法,DP然后记录所有解,但是想想要输出所有解,递归应该可以,很意外的还是TLE了😫
class Solution {
List<String> results = new ArrayList<>();
List<String> result = new ArrayList<>();
public List<String> wordBreak(String s, L...
题意
给一个字符串和一个字符串数组,判断字符串是否能由数组的字符串组合而成,可以重复使用同时不必全部使用TLE解法
TLE的自然是递归了😩
class Solution {
Set<String> used = new HashSet<>();
public boolean wordBreak(String s, List<String> wordDict) {
return search(s, wordDict, 0);
}
boolean search(String s, List<String> wo...
题意给一个数组代表权重,给数组每一个元素赋值,值最小为1,且相邻的元素权重大的值必须大于权重小的
分析
直接给第一个元素赋值1,然后依次比较,有三种情况
ratings[i] > ratings[i - 1],则当前值为前一个的值加1
ratings[i] == ratings[i - 1],则当前值为1
ratings[i] < ratings[i - 1],刚当前值为1,这时候需要处理前一个值也为1的情况,需要往前遍历,将ratings[i - 1]加1
这个解法能AC,但是非常慢
class Solution {
public int candy(int[]...
题意拷贝一个结点的所有子结点,与前面有一题一样的解法
class Solution {
Map<Node, Node> copied = new HashMap<>();
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
if (copied.containsKey(head)) {
return copied.get(head);
}...
题意
一次循环找出数组中唯一一个只出现一次的数字
直接放别人的解吧,好精妙https://blog.csdn.net/Cloudox_/article/details/52459584 public int singleNumber(int[] nums) {
int result = 0;
for(int i=0;i<nums.length;i++) result ^= nums[i];
return result;
}
解释
四行代码就解决了,我们看看它做了什么,先设定一个0,然后循环和数组中的每个数去做异或运算,每次得出的结果都继续和下一...