目录
- 前言
- 一、LRU(全A)
-
- 代码
- 二、合法括号(全A)
-
- 代码
前言
这次的笔试题都是牛客原题哦,祝兄弟们都有心仪的offer
一、LRU(全A)
代码
package youzan;
package youzan;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
public class First {
public static void main(String[] args) {
int[][] matrix = new int[][]{ { 1, 1, 1}, { 1, 2, 2}, { 1, 3, 2}, { 2, 1}, { 1, 4, 4}, { 2, 2}};
System.out.println(Arrays.toString(LRU(matrix, 3)));
}
public static int[] LRU(int[][] operators, int k) {
// write code here
LinkedHashMap<Integer, Integer> lruMap = new LinkedHashMap<>();
ArrayList<Integer> res = new ArrayList<>();
for (int[] oper : operators) {
int key = oper[1];
switch (oper[0]) {
case 1:
int value = oper[2];
if (lruMap.size() < k) {
lruMap.put(key, value);
} else {
Iterator it = lruMap.keySet().iterator();
lruMap.remove(it.next());
lruMap.put(key, value);
}
break;
case 2:
if (lruMap.containsKey(key)) {
int val = lruMap.get(key);
res.add(val);
lruMap.remove(key);
lruMap.put(key, val);
} else {
res.add(-1);
}
break;
}
}
int[] resArr = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
resArr[i] = res.get(i);
}
return resArr;
}
}
二、合法括号(全A)
代码
package youzan;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class Second {
public static void main(String[] args) {
// System.out.println(isVaild("123"));
System.out.println(isVaild("(123)"));
}
public static boolean isVaild(String statement) {
int len = statement.length();
Map<Character, Character> pairs = new HashMap<Character, Character>();
pairs.put(')', '(');
pairs.put(']', '[');
pairs.put('}', '{');
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < len; i++) {
char ch = statement.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
}
}
return stack.isEmpty();
}
}