//1.复制带随机指针的链表
public class MapInterView {
static class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public Node copyRandomList(Node head) {
//1.遍历旧链表,把旧链表的每一个节点、依次插入到map中,key是旧链表节点地址,value是拷贝出来的新节点的地址
Map<Node,Node> map = new HashMap<>();
for (Node cur = head;cur != null;cur = cur.next) {
map.put(cur,new Node(cur.val));
}
//2.再次遍历链表,修改新链表节点中的next和random
for (Node cur = head;cur != null;cur = cur.next) {
//先从map中找到该cur对应的新链表节点
Node newCur = map.get(cur);
newCur.next = map.get(cur.next);
newCur.random = map.get(cur.random);
}
//需要返回新链表的头节点
return map.get(head);
}
//2.宝石与石头
public int numJewelsInStones(String J,String S) {
//先遍历J的所有宝石类型加入到一个set中
Set<Character> set = new HashSet<>();
for (char c:J.toCharArray()) {
set.add(c);
}
//遍历S得到每个元素去set中查找,找到了说明就是宝石
int ret = 0;
for (char c:S.toCharArray()) {
if (set.contains(c)) {
ret++;
}
}
return ret;
}
//3.前k个高频单词
public List<String> topKFrequent(String[] words,int k) {
//1.先统计每个单词出现的次数
Map<String,Integer> map = new HashMap<>();
for (String s: words) {
Integer value = map.getOrDefault(s,0);
map.put(s,value + 1);
}
//2.把这里统计的内容放到ArrayList中
//keySet相当于得到了一个set,set中存放的是所有的key
ArrayList<String> arrayList = new ArrayList<>(map.keySet());
//按照刚才字符串出现的次数,针对arraylist进行排序
//sort默认是按照元素自身大小进行升序排序(string的字典序)
//此处我们需要按照字符串出现次数来降序排序,也就需要通过比较器制定比较规则
/*Collections.sort(arrayList,new MyComparator(map));*/
//也可以创建一个匿名内部类,不知道类名,但知道这个类实现了comparator接口
//这个类只使用一次,用完就丢了,所以匿名
/* Collections.sort(arrayList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int count1 = map.get(o1);
int count2 = map.get(o2);
if (count1 == count2) {
return o1.compareTo(o2);
}
return count2 - count1;
}
});*/
//lambda表达式,本质上是一个匿名方法
Collections.sort(arrayList, (o1, o2) -> {
int count1 = map.get(o1);
int count2 = map.get(o2);
if (count1 == count2) {
return o1.compareTo(o2);
}
return count2 - count1;
});
return arrayList.subList(0,k);//输出下标为0-k的元素
}
static class MyComparator implements Comparator<String>{
private Map<String,Integer> map;
public MyComparator(Map<String, Integer> map) {
this.map = map;
}
@Override
public int compare(String o1, String o2) {
int count1 = map.get(o1);
int count2 = map.get(o2);
if (count1 == count2) {
//string自身也实现了comparable接口,自带字典序的比较功能
//comparaTo就是在使用string默认的比较规则
return o1.compareTo(o2);
}
//count1 - count2 升序排序
//count2 - count1 降序排序
return count2 - count1;
}
}
}