一、
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public class Solution {
//有序数组,可以用二分法
public boolean Find(int target, int [][] array) {
for(int i = 0; i < array.length; i++) {
int left = 0;
int right = array[i].length - 1;
while(left < right) {
int mid = (left + right) / 2;
if(target > array[i][mid]) {
left = mid + 1;
}else if(target > array[i][mid]) {
right = mid - 1;
}else {
return true;
}
}
}
return false;
}
}
二、
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution {
//直接用API
public String replaceSpace(StringBuffer str) {
String res = str.toString().replaceAll(" ", "%20");
return res;
}
}
三、
输入一个链表,从尾到头打印链表每个节点的值。
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
public class Solution {
ArrayList<Integer> res = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
//递归版
if(listNode != null) {
printListFromTailToHead(listNode.next);
res.add(listNode.val);
}
//非递归版,反向容易联想到栈
// Stack<Integer> stk = new Stack<>();
// while(listNode != null) {
// stk.add(listNode.val);
// listNode = listNode.next;
// }
// while(!stk.isEmpty()) {
// res.add(stk.pop());
// }
return res;
}
}
四、
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
public class Solution {
//递归法
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || in.length == 0 || pre == null || in == null){
return null;
}
TreeNode node = new TreeNode(pre[0]);
for(int i = 0; i < in.length; i++){
if(pre[0] == in[i]){
int[] leftPre = new int[i];
int p = 1;
for(int j = 0; j < i; j++) {
leftPre[j] = pre[p++];
}
int[] leftIn = new int[i];
for(int j = 0; j < i; j++) {
leftIn[j] = in[j];
}
int[] rightPre = new int[pre.length - i - 1];
p = i + 1;
for(int j = 0; j < rightPre.length; j++) {
rightPre[j] = pre[p++];
}
int[] rightIn = new int[in.length - i - 1];
p = i + 1;
for(int j = 0; j < rightPre.length; j++) {
rightIn[j] = in[p++];
}
node.left = reConstructBinaryTree(leftPre, leftIn);
node.right = reConstructBinaryTree(rightPre, rightIn);
}
}
return node;
}
}
五、
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//stk1作为入队列栈,stk2作为出队列栈
public void push(int node) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}