2018 cs61b examprep05
https://sp18.datastructur.es/materials/discussion/examprep05.pdf
2 Use them!
a.
类似lc的第一题,直接用代码了
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
res[0]=map.get(nums[i]);
res[1]=i;
return res;
}
map.put(target-nums[i], i);
}
return res;
}
}
b.
先用map把每个word是次数记录下来,然后用优先队列(自己建立排序方法),最后输出。
3
a.
import java.util.Stack;
public class Deque<Item> {
private final Stack<Item> a;
private final Stack<Item> b;
public Deque() {
a = new Stack<Item>();
b = new Stack<Item>();
}
public void push(Item t) {
while (!a.empty()) {
b.push(a.pop());
}
a.push(t);
while (!b.empty()) {
a.push(b.pop());
}
}
public Item poll() {
return a.pop();
}
}
b.在上面的基础上加一个排序规则就好了,就在插入的时候加一个判断
import java.util.Stack;
public class Deque<Item extends Comparable<Item>> {
private final Stack<Item> a;
private final Stack<Item> b;
public Deque() {
a = new Stack<Item>();
b = new Stack<Item>();
}
public void push(Item t) {
while (!a.empty() && a.peek().compareTo(t) < 0) {
b.push(a.pop());
}
a.push(t);
while (!b.empty()) {
a.push(b.pop());
}
}
public Item poll() {
return a.pop();
}
}