提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
其实很多算法题目主要是对知识点的考察和教学意义远大于其工程实践的意义,所以面试题也是这样
一、力扣977. 有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
for(int i = 0, j = nums.length-1, k = j; i <= j ;){
if(nums[i] * nums[i] <= nums[j] * nums[j]){
res[k --] = nums[j] * nums[j];
j --;
}else{
res[k --] = nums[i] * nums[i];
i ++;
}
}
return res;
}
}
二、力扣209. 长度最小的子数组
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int left = 0, right = 0, sum = 0;
while(right < nums.length){
sum += nums[right];
right ++;
while(sum >= target){
res = Math.min(res,right - left);
sum -= nums[left];
left ++;
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
三、力扣232. 用栈实现队列
class MyQueue {
Deque<Integer> deq1 = new LinkedList<>();
Deque<Integer> deq2 = new LinkedList<>();
public MyQueue() {
}
public void push(int x) {
deq1.offerLast(x);
}
public int pop() {
if(deq2.isEmpty()){
while(!deq1.isEmpty()){
int temp = deq1.pollLast();
deq2.offerLast(temp);
}
}
return deq2.pollLast();
}
public int peek() {
if(deq2.isEmpty()){
while(!deq1.isEmpty()){
int temp = deq1.pollLast();
deq2.offerLast(temp);
}
}
return deq2.peekLast();
}
public boolean empty() {
return deq1.isEmpty() && deq2.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
四、力扣225. 用队列实现栈
class MyStack {
Deque<Integer> deq1 = new LinkedList<>();
Deque<Integer> deq2 = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
deq1.offerLast(x);
}
public int pop() {
if(deq1.isEmpty()){
while(deq2.size() > 1){
int temp = deq2.pollFirst();
deq1.offerLast(temp);
}
return deq2.pollFirst();
}
while(deq1.size() > 1){
int temp = deq1.pollFirst();
deq2.offerLast(temp);
}
return deq1.pollFirst();
}
public int top() {
if(deq1.isEmpty()){
while(deq2.size() > 1){
int temp = deq2.pollFirst();
deq1.offerLast(temp);
}
int res = deq2.pollFirst();
deq1.offerLast(res);
return res;
}
while(deq1.size() > 1){
int temp = deq1.pollFirst();
deq2.offerLast(temp);
}
int res = deq1.pollFirst();
deq2.offerLast(res);
return res;
}
public boolean empty() {
return deq1.isEmpty() && deq2.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/