Java知识点
//返回[0, target-1]中随机数
Random r = new Random();
r.nextInt(target);
//在set中取出一个数
set.iterator().next();
//新建list数组 后面不写<>
List[] listArray = new ArrayList[100];
hash概念
705 Design HashSet
*706 Design HashMap
lt128 Hash Function
hash应用
(下面四个题 注意更新的时候 在map中和list中都要更新 注意要删除的元素是否已在末尾的讨论)
*146 LRU Cache map
*380 Insert Delete GetRandom O(1) map
381 Insert Delete GetRandom O(1) - Duplicates allowed map
(O(1)时间删除 想到用map存值和index的对应关系
O(1)时间random 把最后一个数和要处理的数调换位置后删除最后一个数)
lt 960 First Unique Number in a Stream II
杂题
lt138 Subarray Sum 注意要put(0, -1)
138 Copy List with Random Pointer 用hashmap和不用两种方法
**128 Longest Consecutive Sequence 找数组中连续数字的个数
49 Group Anagrams 相同排列为一组 分组
705. Design HashSet
class MyHashSet {
List[] set;
/** Initialize your data structure here. */
public MyHashSet() {
set = new ArrayList[33];
}
public void add(int key) {
int index = key%33;
if(set[index]==null)
set[index] = new ArrayList();
for(Integer num: set[index]){
if(num==key)
return;
}
set[index].add(key);
}
public void remove(int key) {
int index = key%33;
if(set[index]==null)
return;
for(int i=0; i
706. Design HashMap
class MyHashMap {
List[] map;
/** Initialize your data structure here. */
public MyHashMap() {
map = new ArrayList[33];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int index = key%33;
if(map[index]==null)
map[index] = new ArrayList<>();
for(int i=0; i
lt128. Hash Function
public int hashCode(char[] key, int HASH_SIZE) {
// write your code here
long result = 0;
for(int i=0; i
146. LRU Cache
class LRUCache {
class ListNode{
int key, value;
ListNode next;
ListNode(int key, int value, ListNode next){
this.key = key;
this.value = value;
this.next = next;
}
}
ListNode head, tail;
Map map;
int capacity = 0;
int size = 0;
private void moveBack(int key){
ListNode node = map.get(key);
ListNode end = node.next;
if(end==tail)
return;
node.next =end.next;
map.put(node.next.key, node);
tail.next = end;
map.put(key, tail);
tail = end;
}
public LRUCache(int capacity) {
head = new ListNode(0, 0, null);
tail = head;
map = new HashMap<>();
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)){
moveBack(key);
return tail.value;
}else{
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key)){
moveBack(key);
tail.value = value;
}else{
if(size
380. Insert Delete GetRandom O(1)
class RandomizedSet {
List list;
Map map;
int size;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
size = 0;
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)){
return false;
}else{
list.add(val);
map.put(val, size);
size++;
return true;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val))
return false;
int index = map.remove(val);
if(index == size-1){
list.remove(list.size()-1);
}
else{
list.set(index, list.get(size-1));
list.remove(list.size()-1);
map.put(list.get(index), index);
}
size = size-1;
return true;
}
/** Get a random element from the set. */
Random r = new Random();
public int getRandom() {
return list.get(r.nextInt(list.size()));
}
}
381. Insert Delete GetRandom O(1) - Duplicates allowed
class RandomizedCollection {
List nums;
Map> map;
java.util.Random random;
public RandomizedCollection() {
nums = new ArrayList<>();
map = new HashMap<>();
random = new java.util.Random();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean existed = map.containsKey(val);
if(!existed){
Set set = new HashSet<>();
map.put(val, set);
}
map.get(val).add(nums.size());
nums.add(val);
return !existed;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
boolean existed = map.containsKey(val);
if(existed){
int end = nums.size()-1;
if(!map.get(val).contains(end)){
int index = map.get(val).iterator().next();
int lastVal = nums.get(end);
map.get(lastVal).remove(end);
map.get(lastVal).add(index);
map.get(val).remove(index);
map.get(val).add(end);
nums.set(index, lastVal);
}
map.get(val).remove(end);
if(map.get(val).isEmpty())
map.remove(val);
nums.remove(end);
}
return existed;
}
/** Get a random element from the collection. */
public int getRandom() {
return nums.get(random.nextInt(nums.size()));
}
}
387. First Unique Character in a String
class Solution {
public int firstUniqChar(String s) {
return twoIteration(s);
return oneIteration(s);
return noExtraMemory(s);
}
public int twoIteration(String s) {
int[] fq = new int[26];
for(int i=0; i
lt960. First Unique Number in a Stream II
public class DataStream {
class ListNode{
int value;
ListNode next;
ListNode(int value){
this.value = value;
}
}
Map map = new HashMap<>();
Set set = new HashSet<>();
ListNode dummy, tail;
public DataStream(){
// do intialization if necessary
dummy = new ListNode(0);
tail = dummy;
}
/**
* @param num: next number in stream
* @return: nothing
*/
public void add(int num) {
// write your code here
if(set.contains(num)){
if(map.containsKey(num)){
ListNode pre = map.get(num);
if(pre.next==tail){
tail = pre;
}else{
map.put(pre.next.next.value, pre);
pre.next = pre.next.next;
}
map.remove(num);
}
}else{
ListNode newNode = new ListNode(num);
tail.next = newNode;
map.put(num, tail);
tail = newNode;
set.add(num);
}
}
/**
* @return: the first unique number in stream
*/
public int firstUnique() {
// write your code here
return dummy.next.value;
}
}
lt138 Subarray Sum 注意要put(0, -1)
找和为零的子数组
public class Solution {
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number and the index of the last number
*/
public List subarraySum(int[] nums) {
// write your code here
int sum = 0;
List result = new ArrayList<>();
Map map = new HashMap<>();
map.put(0, -1);
for(int i=0; i
138. Copy List with Random Pointer
两种方法
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
return withMap(head);
// return withoutMap(head);
}
public RandomListNode withMap(RandomListNode head) {
if(head==null)
return head;
Map map = new HashMap<>();
RandomListNode newHead = new RandomListNode(head.label);
map.put(head, newHead);
while(head!=null){
RandomListNode next = head.next;
RandomListNode random = head.random;
if(next!=null && !map.containsKey(next)){
RandomListNode newNext = new RandomListNode(next.label);
map.put(next, newNext);
}
if(random!=null && !map.containsKey(random)){
RandomListNode newRandom = new RandomListNode(random.label);
map.put(random, newRandom);
}
if(next!=null)
map.get(head).next = map.get(next);
if(random!=null)
map.get(head).random = map.get(random);
head = head.next;
}
return newHead;
}
public RandomListNode withoutMap(RandomListNode head) {
RandomListNode iter = head, next;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
next = iter.next;
RandomListNode copy = new RandomListNode(iter.label);
iter.next = copy;
copy.next = next;
iter = next;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
RandomListNode pseudoHead = new RandomListNode(0);
RandomListNode copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
// extract the copy
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
// restore the original list
iter.next = next;
iter = next;
}
return pseudoHead.next;
}
}
128. Longest Consecutive Sequence
class Solution {
public int longestConsecutive(int[] nums) {
return On(nums);
// return naive(nums);
}
public int On(int[] nums) {
if(nums==null || nums.length<=0)
return 0;
int max = 0;
Map map = new HashMap<>();
for(int num : nums){
if(map.containsKey(num))
continue;
int left = map.getOrDefault(num-1,0);
int right = map.getOrDefault(num+1, 0);
int sum = left+right+1;
max = Math.max(max, sum);
if(left>0)
map.put(num-left, sum);
if(right>0)
map.put(num+right, sum);
map.put(num, sum);
}
return max;
}
public int naive(int[] nums) {
if(nums==null || nums.length<=0)
return 0;
Arrays.sort(nums);
int pre = nums[0];
int max = 1;
int current = 1;
for(int i=1; i
49. Group Anagrams
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
除了用sort 还可以给每一个字母分配一个质数 成绩相同的是一组
class Solution {
public List> groupAnagrams(String[] strs) {
List> results = new ArrayList<>();
Map> map = new HashMap<>();
for(String str: strs){
String sorted = sort(str);
if(!map.containsKey(sorted)){
map.put(sorted, new ArrayList());
}
map.get(sorted).add(str);
}
for(String str: map.keySet()){
List result = map.get(str);
results.add(result);
}
return results;
}
private String sort(String s){
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}