找出数组中的重复元素
题目:找出整型数组中重复出现的元素
思路:使用哈希表来记录每个元素出现的次数,如果一个元素出现的次数大于1,则说明该元素是重复元素。
public static List<Integer> findDuplicate(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> duplicates = new ArrayList<>();
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
int count = map.get(num);
map.put(num, count + 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
duplicates.add(entry.getKey());
}
}
return duplicates;
}
实现一个LRU Cache
可以借助linkedHashMap来实现。
LinkedHashMap 维护一个双向链表,维护迭代顺序。构造时可以选择访问order或者插入order。
/**
* Constructs an empty {@code LinkedHashMap} instance with the
* specified initial capacity, load factor and ordering mode.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param accessOrder the ordering mode - {@code true} for
* access-order, {@code false} for insertion-order
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int MAX_ENTRIES;
public LRUCache(int initialCapacity, float loadFactor, int maxEntries) {
super(initialCapacity, loadFactor, true);
MAX_ENTRIES = maxEntries;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > MAX_ENTRIES;
}
}
我们继承了LinkedHashMap类,并重写了其中的removeEldestEntry方法。该方法返回true表示需要移除最老的元素,即最久未被访问的元素。我们使用了MAX_ENTRIES变量来控制缓存大小,当超出该值时会自动移除最老的元素。
自己实现
import java.util.*;
public class Solution {
//设置双向链表结构
static class Node{
int key;
int val;
Node pre;
Node next;
//初始化
public Node(int key, int val) {
this.key = key;
this.val = val;
this.pre = null;
this.next = null;
}
}
//哈希表
private Map<Integer, Node> mp = new HashMap<>();
//设置一个头
private Node head = new Node(-1, -1);
//设置一个尾
private Node tail = new Node(-1, -1);
private int size = 0;
public int[] LRU (int[][] operators, int k) {
//构建初始化连接
//链表剩余大小
this.size = k;
this.head.next = this.tail;
this.tail.pre = this.head;
//获取操作数
int len = (int)Arrays.stream(operators).filter(x -> x[0] == 2).count();
int[] res = new int[len];
//遍历所有操作
for(int i = 0, j = 0; i < operators.length; i++){
if(operators[i][0] == 1)
//set操作
set(operators[i][1], operators[i][2]);
else
//get操作