1.复制带随机指针的链表
题目链接:复制带随机指针的链表
private static class Node {
private int val;
private Node next;
private Node random;
private Node() {}
private Node(int val, Node next, Node random) {
this.val = val;
this.next = next;
this.random = random;
}
}
解法1:直接复制
public class CopyRandomList {
public static Node copyRandomList1(Node head){
if(head == null){
return null;
}
//假设head 1-->2-->3-->4
Node cur = head;
//复制成1-->1-->2-->2-->3-->3-->4-->4-->null
while(cur != null){
Node node = new Node();
node.val = cur.val;
node.next = cur.next;
cur.next = node;
cur = node.next;
}
//复制random
cur = head;
while(cur != null){
Node node = cur.next;
if(cur.random != null) { //cur.random可能为空
node.random = cur.random.next;
}
node.random = null; //cur.randon为空 则node.random = null
}
//断开连接 还原链表
cur = head;
Node newHead = head.next;
while(cur != null){
Node node = cur.next;
cur.next = node.next;
if(node.next != null) {
node.next = node.next.next;
}
cur = cur.next;
}
return newHead;
}
}
解法2:利用Map
public class CopyRandomList {
//自定义比较器
private static class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2) {
return o1.val - o2.val;
}
}
public static Node copyRandomList2(Node head) {
//假设head 1-->2-->3-->4
Map<Node, Node> map = new TreeMap<>(new NodeComparator());
//普通链表复制 1-->2-->3-->4 (未复制random)
Node newHead = null;
Node newLast = null;
Node cur = head;
while (cur != null) {
Node node = new Node();
node.val = cur.val;
//尾插
if (newHead == null) {
newHead = node;
} else {
newLast.next = node;
}
newLast = node;
map.put(cur, node); //新旧链表形成对应关系 1--1 2--2 3--3 4--4 (K--Val)
cur = cur.next;
}
//复制random
cur = head;
Node node = newHead;
while (node != null) {
if (cur.random != null) {
//TreeMap内部需要对Key进行大小比较 引用类型无法直接比较大小 需要传进去比较器
node.random = map.get(cur.random);
} else {
node.random = null;
}
cur = cur.next;
node = node.next;
}
return newHead;
}
}
注意:node.random = map.get(cur.random);
1.TreeMap内部需要对Key进行大小比较 引用类型无法直接比较大小 需要传进去比较器
2.在使用到Map、Set时,如果K为引用类型,则需传入比较器
2.宝石和石头
题目链接:宝石与石头
程序测试:利用Set
import java.util.Set;
import java.util.TreeSet;
public class NumJewelsInStones {
public int numJewelsInStones(String J, String S) {
// 把所有宝石放到 Set 中
Set<Character> jewels = new TreeSet<>();
for (char j : J.toCharArray()) {
jewels.add(j);
}
// 遍历所有的石头
int count = 0;
for (char s : S.toCharArray()) {
if (jewels.contains(s)) { //boolean contains(Object o){} 判断o是否在集合中
count++;
}
}
return count;
}
}
注意:遍历字符串的方法
String s;
char[] a = s.toCharArray();//把字符串转化成数组 放在数组a中
for(char c : a){ //循环遍历数组a
}