1)109.有序链表转换为二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return toAVL(head,null);
}
private TreeNode toAVL(ListNode head,ListNode end){//左取右不取
if(head == end) return null;
ListNode slow,fast;
slow = head;
fast = head;
while(fast != end){
if(fast.next != end){
fast = fast.next.next;
slow = slow.next;
}else{
fast = fast.next;
}
}
//此时slow指向中间节点
TreeNode node = new TreeNode(slow.val);
node.left = toAVL(head,slow);
node.right = toAVL(slow.next,end);
return node;
}
2)455.分发饼干
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
注意:
你可以假设胃口值为正。
一个小朋友最多只能拥有一块饼干。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/assign-cookies
public int findContentChildren(int[] g, int[] s) {
if(g == null || s == null || g.length == 0 || s.length == 0) return 0;
int cnt = 0;
Arrays.sort(g);
Arrays.sort(s);
int i = 0;
int j = 0;
while (i < g.length && j < s.length){
if(g[i] <= s[j]){
i++;
j++;
cnt++;
}else{
j++;
}
}
return cnt;
}
3)125.验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-palindrome
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0) return true;
int front = 0,rear = s.length()-1;
while (front <= rear){
while (front < rear && !Character.isAlphabetic(s.charAt(front)) && !Character.isDigit(s.charAt(front)))
front++;
while ( front < rear && !Character.isAlphabetic(s.charAt(rear)) && !Character.isDigit(s.charAt(rear)))
rear--;
if (!s.substring(front,front+1).equalsIgnoreCase(s.substring(rear,rear+1)))
return false;
front++;
rear--;
}
return true;
}
4)414.环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
public boolean hasCycle(ListNode head) {
//快慢指针
ListNode fast,slow;
fast = slow = head;
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
return true;
}
return false;
}
5)142.环形链表Ⅱ
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
public ListNode detectCycle(ListNode head) {
ListNode slow,fast;
fast = slow = head;
boolean hasCycle = false;
//第一次相遇
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if (fast == slow){
hasCycle = true;
break;
}
}
if(hasCycle == false) return null;
//如果有环,则slow从head开始,与fast相同速度前进,再次相遇的点就是要找的环的初始的点
slow = head;
while (fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow;
}