1.二维数组中的查找
因为数组是从左往右递增,从上往下递增,所以我们从左下角开始寻找,如果比目标值小就向右寻找,比目标值大就向上寻找。
public class Solution {
public boolean Find(int target, int [][] array) {
int i = 0;
int j = array.length-1;
while(i<array[0].length&&j>=0){
if(target<array[j][i]){
j--;
}else if(target>array[j][i]){
i++;
}else{
return true;
}
}
return false;
}
}
2.替换空格
把字符串变成数组,遍历数组,如果不是空格就正常添加到Arraylist中,如果是空格,就分别添加'%','2','0'
import java.util.*;
public class Solution {
public String replaceSpace(StringBuffer str) {
ArrayList arr = new ArrayList();
StringBuilder sb = new StringBuilder();
char cha[] = str.toString().toCharArray();
for(char x :cha){
if(x==' '){
arr.add('%');
arr.add('2');
arr.add('0');
}else{
arr.add(x);
}
}
for(int i=0;i<arr.size();i++){
sb.append(arr.get(i));
}
return sb.toString();
}
}
3.从尾到头打印链表
借助一个栈的后进先出功能,先遍历一遍链表,把值存储到栈中,然后再从栈中取出数据即可。
import java.util.ArrayList;
import java.util.*;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList();
Stack<Integer> st = new Stack();
if(listNode==null){
return res;
}
while(listNode!=null){
st.push(listNode.val);
listNode=listNode.next;
}
while(!st.isEmpty()){
res.add(st.pop());
}
return res;
}
}
4.重建二叉树
本题考察二叉树的前序遍历和中序遍历以及递归的用法(在处理二叉树的时候尤其常用),只要遵循两种遍历的特点就可以实现。
最后的递归条件稍微有一点绕,可以画一个例子,只需要按照第一次划分之后情况设定就可以了,递归会把后续的逻辑走下去。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length==0||in.length==0){
return null;
}
return mktree(pre,0,pre.length-1,in,0,in.length-1);
}
public TreeNode mktree(int []pre,int ps,int pe,int []in,int is,int ie){
if(ps>pe){
return null;
}
int temp = pre[ps];
int index = is;
while(index<=ie&&in[index]!=temp){
index++;
}
TreeNode root = new TreeNode(in[index]);
root.left = mktree(pre,ps+1,ps+index-is,in,is,index-1);
root.right =mktree(pre,ps+index-is+1,pe,in,index+1,ie);
return root;
}
}
5.用两个栈实现队列
栈的特点是后进先出,队列的特点是先进先出。
注意:为了保证出队列的顺序,需要在第二个堆栈为空的时候一次性加入堆栈一种的所有数。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (!stack2.isEmpty()){
return stack2.pop();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}