剑指offer
来源:互联网 发布:寂寞聊天软件 编辑:程序博客网 时间:2024/06/05 06:55
public class Solution { public int NumberOf1(int n) { int sum = 0; while (n != 0) { n = n & (n-1); sum++; } return sum; }}
艾瑞巴蒂,我来刷剑指了,因为要找工作了呀~ ^_^ 紧急紧急!!!这里来记录下~
1、二维数组的查找:
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:从右上角开始,比目标大的话往左走;比目标小的话,向下走。
源码:
public class Solution { public boolean Find(int target, int [][] array) { if (array.length == 0) return false; int rows = array.length; int cols = array[0].length; int row = 0; int col = cols - 1; while (row < rows && col >= 0) { if (array[row][col] > target) col --; else if (array[row][col] < target) row ++; else return true; } return false; }}2、替换空格:
题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
思路:用StringBuilder append append 就行了(啊!夏天可不可以不要走呀~~~
源码:
public class Solution{ public String replaceSpace(StringBuffer str) { char[] temp = str.toString().toCharArray(); StringBuilder res = new StringBuilder(); for (int i = 0; i < temp.length; i++) { if (temp[i] == ' ') res.append("%20"); else res.append(temp[i]); } return res.toString(); }}3、从尾到头打印链表:
题目:输入一个链表,从尾到头打印链表每个节点的值。
思路:(原书p59)递归 ok?先递归输出它后面节点,再输出该节点自身。
源码:
/*** public class ListNode {* int val;* ListNode next = null;** ListNode(int val) {* this.val = val;* }* }**/import java.util.ArrayList;public class Solution { public ArrayList<Integer> res = new ArrayList<Integer>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if (listNode != null) { printListFromTailToHead(listNode.next); res.add(listNode.val); }return res; }}4、重建二叉树:
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
思路:(原书P63)根据前序第一个节点可以确定根节点,从而可以在中序里找到左子树节点,右子树节点。然后左子树,右子树递归~
可以建4个数组,分别记左子树前序,左子树中序,右子树前序,右子树中序。(我想看剧,不行!我爱写码,我爱写码,我爱写码)
源码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.util.ArrayList;public class Solution{ public TreeNode reConstructBinaryTree(int [] pre,int [] in) { ArrayList<Integer> p = new ArrayList<Integer>(); ArrayList<Integer> i = new ArrayList<Integer>(); for (int j = 0; j < pre.length; j++) { p.add(pre[j]); i.add(in[j]); } return reConstructBinaryTree2(p, i); } private TreeNode reConstructBinaryTree2(ArrayList<Integer> pre, ArrayList<Integer> in) { if (pre.size() == 0) return null; ArrayList<Integer> leftpre = new ArrayList<Integer>(); ArrayList<Integer> leftin = new ArrayList<Integer>(); ArrayList<Integer> rightpre = new ArrayList<Integer>(); ArrayList<Integer> rightin = new ArrayList<Integer>(); TreeNode root = new TreeNode(pre.get(0)); for (int i = 0 ; i < in.size(); i++) if (in.get(i).equals(pre.get(0))) break; else leftin.add(in.get(i)); for (int i = 0; i < leftin.size(); i++) leftpre.add(pre.get(i+1)); for (int i = leftpre.size()+1; i < pre.size(); i++) { rightpre.add(pre.get(i)); rightin.add(in.get(i)); } root.left = reConstructBinaryTree2(leftpre, leftin); root.right = reConstructBinaryTree2(rightpre, rightin); return root; }}
5、用两个栈实现队列:
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:非常简单了,但是不知道你为啥做这么久,服了。push:直接进到栈1就可以了;pop:如果栈2不空,直接pop,否则把栈1的每个元素pop出来再push到栈2(所谓逆序的逆序就正序了,就是个队列序了,蟹蟹)。这里题目也没让你考虑啥特殊情况,我们就先不考虑。
源码:
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() { int temp; if (!stack2.isEmpty()) temp = stack2.pop(); else { if (!stack1.isEmpty()) { int t = stack1.size(); //请注意 for (int i = 0; i < t; i++) stack2.push(stack1.pop()); } temp = stack2.pop(); } return temp; }}
6、旋转数组的最小数字
题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
思路:经过旋转后的数组,如果左边的值比右边的小,那么最小的数字为最左边的;若大于等于右边,说明最小的还在序列中间,需要分情况讨论,这里用跟mid值比较来二分查找那个最小的值。
源码:
import java.util.ArrayList;public class Solution { public int minNumberInRotateArray(int [] array) { if (array.length == 0) return 0; int lo = 0; int high = array.length - 1; while (array[lo] >= array[high]) { if (lo + 1 == high) return array[high]; int mid = lo + (high - lo) / 2; if (array[mid] < array[lo]) high = mid; else lo = mid; } return array[lo]; }}
7、斐波那契数列
题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
思路:一看就递归,但是不行,递归重复计算太多,栈空间会溢出。哎,哎,哎,好Offer快点来嘛,我想出去玩。
源码:
public class Solution { public int Fibonacci(int n) { if (n == 0) return 0;int[] temp = new int[n+1]; temp[0] = 0; temp[1] = 1; for (int i = 2; i <= n; i++) temp[i] = temp[i-1] + temp[i-2]; return temp[n]; }}
8、跳台阶
题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:一次可以跳一级或两级,那么N级台阶的跳法f(n) = f(n-1) + f(n-2),即先跳一级剩下的台阶的跳法加上跳两级剩下的台阶的跳法。
源码:
public class Solution { public int JumpFloor(int target) { if (target < 3) return target; int[] a = new int[target + 1]; a[0] = 0; a[1] = 1; a[2] = 2; for (int i = 3; i <= target; i++) a[i] = a[i-1] + a[i-2]; return a[target]; }}
题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
思路:同上,f(n) = f(n-1) + f(n-2) + 。。。+f(n-n),可以发现f(n) = 2* f(n-1)
源码:
public class Solution{ public int JumpFloorII(int target) { if (target < 3) return target; int[] a = new int[target+1]; a[0] = 1; a[1] = 1; a[2] = 2; for (int i = 3; i <= target; i++) a[i] = a[i-1] * 2; return a[target]; }}10、矩形覆盖
题目:我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
思路:斐波那契数列,蟹蟹
源码:
public class Solution { public int RectCover(int target) { if (target < 3) return target; int[] a = new int[target+1]; a[0] = 0; a[1] = 1; a[2] = 2; for (int i = 3; i <= target; i++) a[i] = a[i-1] + a[i-2]; return a[target]; }}11、二进制中1的个数
题目:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
思路:一个数每次和比它小1的数做按位与,每次会消掉最右边的1.
源码:
public class Solution { public int NumberOf1(int n) { int sum = 0; while (n != 0) { n = n & (n-1); sum++; } return sum; }}
12、数值的整数次方:
题目:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:非常简单,考虑exponent的 < 0 =0 >0的情况即可。妈妈吗呀快点给我个正式offer吧!我今晚要把这个题刷
源码:
public class Solution{ public double Power(double base, int exponent) { if (exponent == 0) return 1; else if (exponent > 0) { double res = 1; for (int i = 0; i < exponent; i++) res = res * base; return res; } else { double res = 1; for (int i = 0; i < -1 * exponent; i++) res = res * base; return 1 / res; } }}13、调整数组顺序使奇数位于偶数前面
题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:统计奇数偶数个数,开辟临时数组,然后放进来。
源码:
public class Solution { public void reOrderArray(int [] array) { int odd = 0; int ou = 0; int[] array2 = new int[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] % 2 == 0) ou++; else odd++; array2[i] = array[i]; } int jishu = 0; int oushu = odd; for (int i = 0; i < array.length; i++) { if (array2[i] % 2 == 0) { array[oushu] = array2[i]; oushu++; } else { array[jishu] = array2[i]; jishu++; } } }}14、链表中倒数第k个结点
题目:输入一个链表,输出该链表中倒数第k个结点。
思路:链表一般都来两指针!快慢指针,快的先走k-1步,然后一起走,慢的指的就是倒数第k个。注意!k为0 以及 k > 链表长度的情况。
源码:
/*public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class Solution { public ListNode FindKthToTail(ListNode head,int k) { ListNode quick = head; ListNode slow = head; if(head == null || k == 0) return null; for (int i= 0; i < k-1; i++) { quick = quick.next; if (quick == null) return null; } while (quick.next != null) { quick = quick.next; slow = slow.next; } return slow; }}15、反转链表
题目:输入一个链表,反转链表后,输出链表的所有元素。
思路:三个指针,记录改方向,注意!最初头结点的Next要指向Null!
源码:
/*public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class Solution { public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode a = head; ListNode b = head.next; ListNode c = head.next.next; while (b != null) { b.next = a; a = b; b = c; if (c == null) break; c = c.next; } head.next = null; return a; }}16、合并两个排序的链表
题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:递归!递归!递归!
源码:
/*public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { ListNode root = null; if (list1 == null) return list2; if (list2 == null) return list1; if (list1.val < list2.val) { root = list1; root.next = Merge(list1.next, list2); } else { root = list2; root.next = Merge(list1, list2.next); } return root; } }
17、树的子结构
题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:递归~从A的根结往下比,可以用Equals比较,相等了则为其子结构。注意边界条件。
源码:
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution{ public boolean HasSubtree(TreeNode root1,TreeNode root2) { boolean left = true; boolean right = true; if (root1 == null || root2 == null) return false; if (isEqual(root1, root2)) return true; //如果两树相等,直接返回true left = HasSubtree(root1.left, root2); //否则比较左子树 right = HasSubtree(root1.right, root2);//否则比较右子树 return (left || right); } public boolean isEqual(TreeNode root1, TreeNode root2) { if (root1 == null && root2 == null) return true; else if (root1 != null && root2 == null) return true; else if (root1 == null && root2 != null) return false; else if (root1 != null && root2 != null) { if (root1.val != root2.val) return false; } return isEqual(root1.left, root2.left) && isEqual(root1.right, root2.right); }}18、树的子结构
题目:操作给定的二叉树,将其变换为源二叉树的镜像。
思路:交换结点的左右子树,递归变换左子树,递归变换右子树。
源码:
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution{ public void Mirror(TreeNode root) { if (root == null) return; TreeNode tmp = root.left; root.left = root.right; root.right = tmp; Mirror(root.left); Mirror(root.right); }}19、顺时针打印矩阵
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路:定义一个start,把从左到右,从上到下,从右到左,从下到上看作一个流程;start记录开始一轮流程的初始位置,当start * 2 < cols && start * 2 < rows时,进行一轮打印;start递增1;循环。
源码:
import java.util.ArrayList;public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> res = new ArrayList<Integer>(); int rows = matrix.length; if (rows == 0) return res; int cols = matrix[0].length; int start = 0; while (start * 2 < rows && start * 2 < cols) //开始的横纵坐标值*2 必须小于行数和列数 { printMatrix2(matrix, res, rows, cols, start); //打印几圈 start++; //!!!注意更新 } return res; } private void printMatrix2(int[][] matrix, ArrayList<Integer> res, int rows,int cols, int start) { int endX = rows - 1 - start; int endY = cols - 1 - start; for (int i = start; i <= endY; i++)//打印从左到右 res.add(matrix[start][i]); if (start < endX) //有两行及以上才可以从上往下打印 for (int i = start + 1; i <= endX; i++) //打印从上到下 res.add(matrix[i][endY]); if (start < endX && start < endY) //至少两行两列才能从右往左打印 for (int i = endY - 1; i >= start; i--)//从右到左打印 res.add(matrix[endX][i]); if (endX - start > 1 && start < endY) //至少三行两列才用从下往上打印 for (int i = endX - 1; i > start; i--) //从下到上打印 res.add(matrix[i][start]); return; }}20、包含min函数的栈
题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路:多定义一个栈专门记录当下栈中的最小值,每次进栈判断,若需进栈元素小于之前的最小值,那么就将此元素进栈,否则还将之前最小值进栈。
源码:
import java.util.Stack;public class Solution{Stack<Integer> res = new Stack<Integer>(); //栈结构 Stack<Integer> tmp = new Stack<Integer>(); //存储当前栈状态下最小值 public void push(int node) { res.push(node); if (tmp.size() == 0) //若tmp栈为空,则当前Node为最小,直接进栈 { tmp.push(node); } else { if (tmp.peek() > node) //tmp栈不空, 若当前node 小于 tmp栈中最小元素,则将node进栈,作为当下最小元素 tmp.push(node); else //否则,把tmp栈中最小的元素即栈顶元素再进栈,因为就算进了node,最小值依旧是最小的 tmp.push(tmp.peek()); } } public void pop() { if (res.size() > 0) { tmp.pop(); //两个都直接出,若z栈不空 res.pop(); } } public int top() { return res.peek(); } public int min() { return tmp.peek(); }}21、栈的压入,弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:模拟栈的压入、弹出,最后栈为空则出栈顺序合理,否则false。
源码:
import java.util.ArrayList;import java.util.Stack;public class Solution { public boolean IsPopOrder(int [] pushA,int [] popA) { if (pushA.length != popA.length) return false; //如果两数组长度不同,那么必然不是出栈顺序 int i = 0;//入栈数组的指针 int j = 0;//出栈数组的指针 Stack<Integer> tmp = new Stack<Integer>(); //模拟进栈出栈的栈 while (i < pushA.length) { while (i < pushA.length-1 && pushA[i] != popA[j]) //找到与出栈数组元素相等的入栈数组元素 { tmp.push(pushA[i]); //相等之前的入栈数组元素都进栈 i++; } tmp.push(pushA[i]); while (tmp.peek() == popA[j]) //开始根据出栈顺序出栈 { tmp.pop(); j++; if (tmp.size() == 0) break; } i++; } if (tmp.size() == 0) return true; //栈空则代表是合理的栈的弹出顺序 else return false; }}
22、从上往下打印二叉树
题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印
思路:先把根节点加进去,只要队列不空,取队列头出队,记录其值,将队列头的左右结入队。
源码:
import java.util.ArrayList;/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution{ public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> res = new ArrayList<Integer>(); //保存要输出的值 ArrayList<TreeNode> tmp = new ArrayList<TreeNode>(); if (root == null) return res; tmp.add(root); while (tmp.size() != 0) //只要队列不空,就移除队列头结点,记录结点值,将其左右子节点压入队列。 { TreeNode t = tmp.remove(0); res.add(t.val); if (t.left != null) tmp.add(t.left); if (t.right != null) tmp.add(t.right); } return res; }}
23、二叉搜索树的后序遍历序列:
题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:数组最后一个元素为根,从左向右比较找出第一个比根大的就是其右子树开始的位置,向右遍历,看右子树值是否都大于根,若小于返回false;递归检查左右子树是否符合要求
源码:
public class Solution{ public boolean VerifySquenceOfBST(int [] sequence) { if (sequence.length == 0) return false; return VerifySequenceOfBST2(sequence, 0, sequence.length - 1); } private boolean VerifySequenceOfBST2(int[] sequence, int start, int end) { if (start >= end) return true; //注意!否则数组越界 int tmp = sequence[end]; //后序遍历,最后一个为根 int i = start; for (i = start; i < end; i++) //从左往右找到第一个比根大的值,其左边的应该为左子树 { if (sequence[i] > tmp) break; } for (int j = i; j < end; j++) //往右查找,若有比根小的值,则不是二叉搜索树后续遍历结果 { if (sequence[j] < tmp ) return false; } boolean left = true; //递归检查左右子树 boolean right = true; left = VerifySequenceOfBST2(sequence, start, i-1); right = VerifySequenceOfBST2(sequence, i, end - 1); return left && right; }}//[4,8,6,12,16,14,10]
24、二叉树中和为某一值的路径
题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:深搜递归
源码:
import java.util.ArrayList;/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (root == null) return res; ArrayList<Integer> temp = new ArrayList<Integer>(); int now = 0; dfs(res, temp, target, root, now); return res; } private void dfs(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> temp, int target, TreeNode root, int now) { if (root != null) //当前结点不为空,加上 { now += root.val; temp.add(root.val); } if (root.left != null) dfs(res, temp, target, root.left, now); //左子树不为空 递归 if (root.right != null) dfs(res, temp, target, root.right, now);//右子树不为空,递归 //左右子树均为空,说明该结点为叶结点,比较是否为target if (root.left == null && root.right == null) { //如果相等,为一条路径,加进数组里 if (now == target) { ArrayList<Integer> anew = new ArrayList<Integer>(); for (int i = 0; i < temp.size(); i++) { anew.add(temp.get(i)); } res.add(anew); } } //注意回退位置! temp.remove(temp.size() - 1); now -= root.val; }}
- 剑指OFFER
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 《剑指offer》
- 剑指Offer
- 剑指offer
- 剑指offer
- 手持端手机端移动端车牌识别介绍
- va_list及vsnprintf的用法
- GP TEE标准体系一张图
- poj3278简单BFS
- 位运算---整数的二进制表达中有多少个1
- 剑指offer
- JavaScript引入错误
- 选择排序
- Java计算两点间的距离
- android sdk 镜像下载方法
- 53. Maximum Subarray
- 框架导出word
- UnityShader从入门到放弃(二)表面着色器和顶点、片元着色器
- JavaSE (十)面向对象之封装续......