771.给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jewels-and-stones
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < jewels.length(); i++) {
set.add(jewels.charAt(i));
}
//遍历 stones,判定当前字符是否存在
int count = 0;
for (int i = 0; i < stones.length(); i++) {
if(set.contains(stones.charAt(i))){
count++;
}
}
return count;
}
}
138.给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
//1.先遍历旧链表,把每个旧节点都创建对应的新节点,并且插入到 Map 中
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 oldNode = head; oldNode != null; oldNode = oldNode.next){
//把 next 相互连接
Node newNode = map.get(oldNode);
Node newNodeNext = map.get(oldNode.next);
newNode.next = newNodeNext;
//把 random 相互连接
Node newNodeRandom = map.get(oldNode.random);
newNode.random = newNodeRandom;
}
return map.get(head);
}
}