LC260. 只出现一次的数字 III
//做了很多道只出现多少次的数字,都采用哈希映射采用空间换时间
class Solution {
public int[] singleNumber(int[] nums) {
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
int[] ans = new int[2];
int index = 0;
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
if (entry.getValue() == 1) {
ans[index++] = entry.getKey();
}
}
return ans;
}
}
LC117. 填充每个节点的下一个右侧节点指针 II
//树的层次遍历采用队列。
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null)
return null;
Queue<Node> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
Node pre = null;
while(len != 0){
Node node = queue.poll();
if(pre != null){
pre.next = node;
}
pre = node;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
len--;
}
}
return root;
}
}
LC395. 至少有 K 个重复字符的最长子串
//要求这个最长子串的每个字符的重复长度都要大于k,那么我们可以考虑分治算法,将大的s字符串进行分割,我们将每个字符小于2的子字符串进行拆分,从不包含该字符的子字符串中进行查找。
class Solution {
public int longestSubstring(String s, int k) {
if(s.length() < k)
return 0;
HashMap<Character,Integer> counter = new HashMap();
for(char ch : s.toCharArray()){
counter.put(ch,counter.getOrDefault(ch,0) + 1);
}
for(char ch : counter.keySet()){
if(counter.get(ch) < k){
int res = 0;
for(String split : s.split(String.valueOf(ch))){
res = Math.max(res,longestSubstring(split,k));
}
return res;
}
}
return s.length();
}
}