1. copy-list-with-random-pointer
Description
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Solution
Create all nodes then link the random and next node.
Code
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
import java.util.ArrayList;
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
//create all nodes
ArrayList<RandomListNode> list = new ArrayList<>();
ArrayList<Integer> labels = new ArrayList<>();
RandomListNode p = head;
while(p!=null){
list.add(new RandomListNode(p.label));
labels.add(p.label);
p = p.next;
}
list.add(null);
p = head;
int pointer = 0;
while(p!=null){
if(p.random!=null)
list.get(pointer).random = list.get(labels.indexOf(p.random.label));
else
list.get(pointer).random = null;
list.get(pointer).next = list.get(pointer+1);
pointer++;
p = p.next;
}
return list.get(0);
}
}
2. single-number-ii
Description
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution
reference: https://www.nowcoder.com/profile/2343147/codeBookDetail?submissionId=20452002
Code
without using extra memory
public int singleNumber(int[] A) {
int ones = 0, twos = 0;
for(int i = 0; i < A.length; i++){
ones = (ones ^ A[i]) & ~twos;
twos = (twos ^ A[i]) & ~ones;
}
return ones;
}
use extra memory
import java.util.*;
public class Solution {
public int singleNumber(int[] A) {
Map<Integer, Boolean> map = new HashMap<>();
for(int i = 0; i < A.length; i++){
if(map.containsKey(A[i])){
map.put(A[i], false);
}else{
map.put(A[i], true);
}
}
for(Integer key: map.keySet()){
if(map.get(key)){
return key;
}
}
return -1;
}
}
3. single-number
Description
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Code
public class Solution {
public int singleNumber(int[] A) {
int num = 0;
for(int i=0;i<A.length;i++){
num = (num ^ A[i]);
}
return num;
}
}