逆波兰表达式求和
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<Integer>();
for(int i = 0; i < tokens.length; i++)
{
String str = tokens[i];
if(str.equals("+") || str.equals("-") || str.equals("*")|| str.equals("/"))
/*java字符串比较”==“是比较地址,”str.equals()“*/
{
//a str b
int b = st.pop();
int a = st.pop();
switch(str.charAt(0)){
case '+': {st.push((a + b)); break;}
case '-': {st.push((a - b)); break;}
case '*': {st.push((a * b)); break;}
case '/': {st.push((a / b)); break;}
}
}
else{
//System.out.println(str);
st.push(Integer.parseInt(str));
}
}
return st.peek();
}
}
总结:
字符串转为数字的方法Integer.parseInt(str)
滑动窗口最大值
java数据结构deque详解
https://blog.csdn.net/devnn/article/details/82716447
class MyDeque {
Deque<Integer> que = new LinkedList<>();
void add(int val){
while(!que.isEmpty() && que.getLast() < val)
que.removeLast();//移除队尾元素
que.offer(val);
}
void poll(int val){
if(!que.isEmpty() && que.peek() == val)
que.poll();//移除队首元素
}
int peek (){
return que.peek();//取队首元素
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
if(k == 1) return nums;
int[] res = new int[(len - k + 1)]; int idx = 0;
MyDeque deque = new MyDeque();
for(int i = 0; i < k; i++) deque.add(nums[i]);
res[idx++] = deque.peek();//先加入前三个的起始答案
for(int i = k; i < len; i++)
{
deque.poll(nums[i - k]);
deque.add(nums[i]);
res[idx++] = deque.peek();
}
return res;
}
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
for (int num : nums) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}
// int[] 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int num = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (queue.peek()[1] < count) {
queue.poll();
queue.offer(new int[]{num, count});
}
} else {
queue.offer(new int[]{num, count});
}
}
int[] ret = new int[k];
for (int i = 0; i < k; ++i) {
ret[i] = queue.poll()[0];
}
return ret;
}
}