1、只出现一次的数字
只出现一次的数字链接
解题思路及代码
/**
* 思路:
* 方法一:
* key-value模型,数字是key,出现次数是val
* 将数组放入map中
* 用map找到val为1的key
*
* 方法二:
* 两个相同的数异或后结果为0
* 任意数与0异或还是自己
* 所有数异或结果就是只出现一次的数
*/
public class SingleNumber {
public int singleNumber1(int[] nums) {
Map<Integer,Integer> map = new TreeMap<>();
for (int n : nums){
int count = map.getOrDefault(n,0);
map.put(n,count+1);
}
for (Map.Entry<Integer,Integer> e : map.entrySet()){
int n = e.getKey();
int c = e.getValue();
if (c == 1){
return n;
}
}
return -1;
}
public int singleNumber2(int[] nums) {
int r = 0;
for (int n : nums){
r = r ^ n;
}
return r;
}
}
总结:
- 任意数异或自己本身,结果为0;
- 任意数异或0,结果不变;
2、复制带随机指针的链表
解题思路及代码
/**
* 思路:
* 方法一:
* 按照链表的方式复制
* 难点:(Random)指向找到新链表的节点(Random)指向
* 1.将旧链表结点复制一份
* 2.将新旧链表连起来
* 3.根据旧链表的Random找新链表的Random
* 4.结束后将新旧链表分开
*
* 方法二:
* 通过Map保存新旧链表的映射关系
* 旧链表中的结点作为key,新链表中的结点作为value;
* 新链表node,旧链表cur
* node.random = map.get(cur.random)
* 解释:cur.random是key,get(cur.random)是key对应的value。
*/
public class CopyList {
public Node copyRandomList(Node head){
Node cur = head;
while (cur != null){
Node node = new Node();
node.val = cur.val;
node.next = cur.next;
cur.next = node;
cur = node.next;
}
cur = head;
//复制random
while (cur != null){
if (cur.