剑指Offer
- 2.2 编程语言
- 2.3数据结构
- 面试题3:二维数组中的查找
- 面试题14:调整数组顺序使奇数位于偶数前面
- 面试题19:二叉树的镜像
- 面试题20:顺时针打印矩阵
- 面试题21:包含min函数的栈
- 面试题22:栈的压入、弹出序列
- 面试题23:从上往下打印二叉树
- ==面试题24:二叉搜索树的后序遍历序列==
- 面试题25:二叉树中和为某一值的路径
- ==面试题26:复杂链表的复制==
- 面试题27:二叉搜索树与双向链表
- 面试题28:字符串的排列
- 面试题29:数组中出现次数超过一半的数字
- 面试题30:最小的K个数
- 面试题31:连续子数组的最大和
- 面试题33:把数组排成最小的数
- ==面试题34:丑数==
- 面试题35:第一个只出现一次的字符
- 面试题36:两个链表的第一个公共结点
- 面试题37:数字在排序数组中出现的次数
- ==面试题40:数组中只出现一次的数字==
- ==面试题41-1:和为S的连续正数序列==
- 面试题41-2:和为S的两个数字
- 面试题42:翻转单词顺序VS左旋转字符串
- 面试题44:扑克牌顺子
- 面试题45:孩子们的游戏(圆圈中最后剩下的数)
- 面试题49:把字符串转换成整数
- 面试题52:构建乘积数组
- 面试题54:表示数值的字符串
- 面试题55:字符流中第一个不重复的字符
- ==面试题56:链表中环的入口结点==
- 面试题57:删除链表中重复的结点
- 面试题59:对称的二叉树
- 面试题61:按之字形顺序打印二叉树
- 面试题60:把二叉树打印成多行
- 面试题63:二叉搜索树的第k个结点
- _面试题65:滑动窗口的最大值_
2.2 编程语言
面试题2: 实现Singleton模式
/**
* @ClassName: Singleton
* @Description: 静态内部内
* @author hf寒沨
* @date 2019年4月7日 下午4:55:39
*
*/
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private static class SingletonHolder {
private final static Singleton instance = new Singleton();
}
}
注解:定义一个私有的内部类,在第一次用这个嵌套类时,会创建一个实例。而类型为SingletonHolder的类,只有在Singleton.getInstance()中调用,由于私有的属性,他人无法使用SingleHolder,不调用Singleton.getInstance()就不会创建实例。
优点:达到了lazy loading的效果,即按需创建实例。
2.3数据结构
面试题3:二维数组中的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
public boolean Find(int target, int[][] array) {
if (array == null || array[0] == null) {
return false;
}
int row = 0;
int columns = array[0].length;
int column = columns - 1;
if (target < array[0][0]) {
return false;
}
while (row < array.length && column >= 0) {
if (array[row][column] == target) {
return true;
} else if (array[row][column] > target) {
column--;
} else {
row++;
}
}
return false;
}
面试题14:调整数组顺序使奇数位于偶数前面
题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:时间换空间
public void reOrderArray(int[] array) {
if (array == null || array.length < 2) {
return;
}
// 记录左边奇数的末位
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0 && i >= index) {
int t = array[i];
// i和index中全为偶数,为了保持顺序不变,整体往后移动
for (int j = i; j > index; j--) {
array[j] = array[j - 1];
}
// 将奇数移动到前面奇数末位
array[index] = t;
index++;
}
}
// 输出测试
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
面试题19:二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
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);
}
面试题20:顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> lists = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return lists;
}
int dr = 0, dc = 0;
int tr = matrix.length - 1, tc = matrix[0].length - 1;
while (dr <= tr && dc <= tc) {
iteratorMatrix(matrix, lists, dr++, dc++, tr--, tc--);
}
for (int i : lists) {
System.out.print(i + " ");
}
return lists;
}
// 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
public void iteratorMatrix(int[][] matrix, ArrayList<Integer> lists, int dr, int dc, int tr, int tc) {
if (tr == dr) {
// 只有一行时
for (int i = dc; i <= tc; i++) {
lists.add(matrix[tr][i]);
}
} else if (tc == dc) {
// 只有一列时
for (int i = dr; i <= tr; i++) {
lists.add(matrix[i][tc]);
}
} else { // 正常
int index = dc;
while (index < tc) {
lists.add(matrix[dr][index++]);
}
index = dr;
while (index < tr) {
lists.add(matrix[index++][tc]);
}
index = tc;
while (index > dc) {
lists.add(matrix[tr][index--]);
}
index = tr;
while (index > dr) {
lists.add(matrix[index--][dc]);
}
}
}
面试题21:包含min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;
/**
* @ClassName: MinStack
* @Description:
* @author hf寒沨
* @date 2019年4月8日 下午11:30:59
*
*/
public class MinStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
private int minData = Integer.MAX_VALUE;
public void push(int node) {
stack.push(node);
minData = Math.min(minData, node);
minStack.push(minData);
}
public void pop() {
stack.pop();
minStack.pop();
minData = minStack.peek();
}
public int top() {
return stack.peek();
}
public int min() {
return minData;
}
}
面试题22:栈的压入、弹出序列
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
public boolean IsPopOrder(int[] pushA, int[] popA) {
Stack<Integer> stack = new Stack<>();
int cur = 0, index = 0;
while (cur <= pushA.length) {
if (stack.isEmpty() || stack.peek() != popA[index]) {
if (cur == pushA.length) { // 已全部入栈
break;
}
stack.push(pushA[cur++]);
}
if (stack.peek() == popA[index]) {
// 当栈顶和弹出序列当前位相等则弹出
stack.pop();
index++;
}
}
if (stack.isEmpty()) {
return true;
}
return false;
}
面试题23:从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (root == null) {
return list;
}
ArrayList<TreeNode> tree = new ArrayList<>();
tree.add(root);
while (tree.size() > 0) {
TreeNode node = tree.remove(0);
list.add(node.val);
if (node.left != null) {
tree.add(node.left);
}
if (node.right != null) {
tree.add(node.right);
}
}
return list;
}
面试题24:二叉搜索树的后序遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
public boolean VerifySquenceOfBST(int[] sequence) {
if (sequence == null || sequence.length < 1) {
return false;
}
return verifySub(sequence, 0, sequence.length - 2, sequence.length - 1);
}
public boolean verifySub(int[] nums, int i, int j, int root) {
// 已无子树,返回true
if (i >= j) {
return true;
}
// 避免只有左子树时,划分错误,初始化使用根节点指针
int mid = root;
for (int cur = i; cur <= j; cur++) {
if (nums[root] < nums[cur]) {
mid = cur;
break;
}
}
for (int cur = i; cur <= j; cur++) {
// 检查左右子树是否搜索二叉树条件
if (cur < mid && nums[cur] < nums[root]) {
continue;
} else if (cur >= mid && nums[cur] >= nums[root]) {
continue;
} else {
return false;
}
}
// 递归检验左右子树
return verifySub(nums, i, mid - 2, mid - 1) && verifySub(nums, mid, j - 1, j);
}
面试题25:二叉树中和为某一值的路径
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路:回溯算法
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
if (root == null) {
return lists;
}
ArrayList<Integer> list = new ArrayList<Integer>();
getPath(lists, list, root, 0, target);
return lists;
}
/*
* count:计算已遍历节点的和
*/
public void getPath(ArrayList<ArrayList<Integer>> lists, ArrayList<Integer> list, TreeNode node, int count,
int target) {
// 记录节点
list.add(node.val);
// 该节点为叶子节点
if (node.left == null && node.right == null) {
// 加上该叶子值是否为目标值
if ((count + node.val) == target) {
lists.add(new ArrayList<Integer>(list));
}
} else {
if (node.left != null) { // 左孩子不为空
getPath(lists, list, node.left, count + node.val, target);
}
if (node.right != null) { // 右孩子不为空
getPath(lists, list, node.right, count + node.val, target);
}
}
// 返回上一个堆栈移除本堆栈中添加节点信息
list.remove(list.size() - 1);
}
面试题26:复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null) {
return null;
}
pHead = cloneNode(pHead);
pHead = cloneRandomPoint(pHead);
return splitRandomListNode(pHead);
}
// 克隆节点,同时插入到被克隆节点后
public RandomListNode cloneNode(RandomListNode head) {
RandomListNode node = head;
while (node != null) {
RandomListNode clone = new RandomListNode(node.label);
clone.next = node.next;
node.next = clone;
node = clone.next;
}
return head;
}
// 复制random指针
public RandomListNode cloneRandomPoint(RandomListNode head) {
RandomListNode node = head;
while (node != null) {
// 判断不为空
if (node.random != null) {
// 克隆节点紧跟其后,克隆节点random
node.next.random = node.random.next;
}
node = node.next.next;
}
return head;
}
// 拆分出克隆链表
public RandomListNode splitRandomListNode(RandomListNode head) {
RandomListNode cloneList = new RandomListNode(-1);
RandomListNode ret = cloneList;
RandomListNode node = head;
while (node != null) {
cloneList.next = node.next;
cloneList = cloneList.next;
node.next = cloneList.next;
node = node.next;
}
return ret.next;
}
面试题27:二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/*
* 二叉搜索树与双向链表
*/
public TreeNode Convert(TreeNode pRootOfTree) {
convertNode(pRootOfTree, null);
TreeNode head = pRootOfTree;
while (head != null && head.left != null) {
head = head.left;
}
return head;
}
/*
* last指向转换好的双向链表的末端
*/
public TreeNode convertNode(TreeNode node, TreeNode last) {
if (node == null) {
return last;
}
if (node.left != null) {
last = convertNode(node.left, last);
}
node.left = last;
if (last != null) {
last.right = node;
}
// the last point
last = node;
if (node.right != null) {
last = convertNode(node.right, last);
}
return last;
}
面试题28:字符串的排列
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
思路:采用回溯法,同时使用数组记录字符串中已使用的位置
public ArrayList<String> Permutation(String str) {
ArrayList<String> lists = new ArrayList<String>();
if (str == null || str.length() == 0) {
return lists;
}
char[] ch = str.toCharArray();
ArrayList<Character> list = new ArrayList<Character>();
// used记录该字符是否添加
boolean[] used = new boolean[ch.length];
for (int i = 0; i < ch.length; i++) {
list.add(ch[i]);
used[i] = true;
getPermutation(lists, list, ch, used, ch.length, 0);
list.remove(list.size() - 1);
used[i] = false;
}
return lists;
}
public void getPermutation(ArrayList<String> lists, ArrayList<Character> list, char[] ch, boolean[] used, int len,
int index) {
if (list.size() >= len) {
StringBuilder sb = new StringBuilder();
for (char c : list) {
sb.append(c);
}
String st = sb.toString();
if (!lists.contains(st)) {
lists.add(sb.toString());
}
return;
} else {
for (int i = 0; i < ch.length; i++) {
if (!used[i]) {
list.add(ch[i]);
used[i] = true;
getPermutation(lists, list, ch, used, len, i + 1);
list.remove(list.size() - 1);
used[i] = false;
}
}
}
}
面试题29:数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解法一:基于排序再查找
解法二:根据数组的特点找出O(n)的算法
算法思路:
- 定义两个变量,一个tmp保存数组中的数,一个count存放次数;
- 当遍历到下一个数字时,和tmp中存放值相同,则加1,否则减1;
- 当次数为0时,保存当前遍历到的数,同时设count为1,直到遍历结束。
- 最后一次把次数设为1时的数字可能满足题目需要,再做验证。
public int MoreThanHalfNum_Solution(int[] array) {
if (array == null || array.length == 0) {
return 0;
}
int count = 1;
int ret = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == ret) {
count++;
} else {
if (--count == 0) {
ret = array[i];
count = 1;
}
}
}
return isMoreThanHalf(array, ret) ? ret : 0;
}
/*
* 验证是否满足出现次数比数组长度一半大的条件
*/
public boolean isMoreThanHalf(int[] array, int k) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == k) {
count++;
}
}
if (count * 2 <= array.length) {
return false;
}
return true;
}
面试题30:最小的K个数
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
思路:最常用的n*log(n)解法是利用堆求解topK问题;最早是再左程云的书上看到利用堆求解,那是真的手写堆,利用链表做存储,我是真的看了两遍,手写了两遍,有时间可以仔细看看,了解堆的特性以及实现。在笔试中还是建议Java用优先队列实现堆。
/*
* 最小的K个数
*/
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (k <= 0 || k > input.length) {
return list;
} else {
// 自定义 Comparator<Integer> cmp;
// 大根堆使用e2-e1
Comparator<Integer> cmparator = new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
return e2 - e1;
}
};
Queue<Integer> queue = new PriorityQueue<>(k, cmparator);
for (int i : input) {
if (queue.size() < k) {
queue.add(i);
} else if (queue.peek() > i) {
queue.poll();
queue.add(i);
} else {
continue;
}
}
while (queue.size() > 0) {
list.add(queue.poll());
}
}
return list;
}
面试题31:连续子数组的最大和
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
思路:动态规划,该题应该算是典型动态规划求解问题;
递归公式:
f
(
n
)
=
{
f
(
n
−
1
)
+
n
u
m
s
[
n
]
,
n
!
=
0
&
f
(
n
−
1
)
>
0
n
u
m
s
[
n
]
,
n
=
0
o
r
f
(
n
−
1
)
<
=
0
;
f(n) = \biggl\{^{nums[n] \space, n=0 or f(n-1)<=0;} _{f(n-1)+nums[n], \space n!=0 \&f(n-1)>0}
f(n)={f(n−1)+nums[n], n!=0&f(n−1)>0nums[n] ,n=0orf(n−1)<=0;
(画出这个公式有点不容易啊)
/*
* 连续子数组的最大和
*/
public int FindGreatestSumOfSubArray(int[] array) {
if (array == null || array.length == 0) {
return 0;
}
int max = array[0];
int count = array[0];
for (int i = 1; i < array.length; i++) {
count = count > 0 ? count + array[i] : array[i];
max = Math.max(max, count);
}
return max;
}
面试题33:把数组排成最小的数
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路:1.最常规的操作是找出所有拼接种类,再找出最小的;耗时较大,不建议。
2.两个数m,n能拼接成mn, nm。如果mn<nm,此时应打印mn。
因此,当mn<nm时,我们可定义m<n;
反之,mn>nm时,可定义m>n;
以及mn=nm时,定义m=n;
具体证明可查看剑指Offer.
在Java,只需要重写Comparator中compare方法即可实现。
/**
* 把数组排成最小的数
* @param numbers
* @return
*/
public String PrintMinNumber(int[] numbers) {
if (numbers == null || numbers.length <= 0) {
return "";
}
String[] st = new String[numbers.length];
for (int i = 0; i < numbers.length; i++) {
st[i] = String.valueOf(numbers[i]);
}
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String st1 = o1+o2;
String st2 = o2+o1;
return st1.compareTo(st2);
}
};
Arrays.sort(st, comparator);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < st.length; i++) {
sb.append(st[i]);
}
return sb.toString();
}
面试题34:丑数
题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
/**
* 丑数
*
* @param index
* @return
*/
public int GetUglyNumber_Solution(int index) {
if (index < 1) {
return 0;
} else if (index == 1) {
return 1;
}
int[] nums = new int[index];
nums[0] = 1;
int next = 1;
int t2 = 0;
int t3 = 0;
int t5 = 0;
while (next < index) {
// 只要tn*n还小于index,可继续往后移动
nums[next] = getMin(nums[t2] * 2, nums[t3] * 3, nums[t5] * 5);
while (nums[t2] * 2 <= nums[next]) {
t2++;
}
while (nums[t3] * 3 <= nums[next]) {
t3++;
}
while (nums[t5] * 5 <= nums[next]) {
t5++;
}
next++;
}
return nums[index - 1];
}
public int getMin(int n1, int n2, int n3) {
int min = (n1 < n2) ? n1 : n2;
min = (min < n3) ? min : n3;
return min;
}
面试题35:第一个只出现一次的字符
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路:使用哈希表
/**
* 第一个只出现一次的字符
* @param str
* @return
*/
public int FirstNotRepeatingChar(String str) {
if (str == null || str.length() == 0) {
return -1;
}
int[] map = new int[58];
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
map[ch[i] - 'A']++;
}
for (int i = 0; i < ch.length; i++) {
if (map[ch[i] - 'A'] == 1) {
return i;
}
}
return -1;
}
面试题36:两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
int m = getLength(pHead1);
int n = getLength(pHead2);
ListNode p = pHead1;
ListNode q = pHead2;
int k = m - n;
if (m < n) {
p = pHead2;
k = -k;
q = pHead1;
}
while (k > 0) {
p = p.next;
k--;
}
while (q != null && p != null) {
if (q == p) {
return p;
}
p = p.next;
q = q.next;
}
return null;
}
public int getLength(ListNode head) {
int count = 0;
ListNode node = head;
while (node != null) {
count++;
node = node.next;
}
return count;
}
面试题37:数字在排序数组中出现的次数
题目描述
统计一个数字在排序数组中出现的次数。
/**数字在排序数组中出现的次数
*
*
* @param array
* @param k
* @return
*/
public int GetNumberOfK(int[] array, int k) {
if (array == null || array.length == 0) {
return 0;
}
int left = getLeftIndex(array, k, 0, array.length - 1);
if (left == -1) {
return 0;
}
int right = getRightIndex(array, k, left, array.length - 1);
if (right == -1) {
return 0;
}
return right - left + 1;
}
public int getLeftIndex(int[] array, int k, int start, int end) {
if (start > end) {
return -1;
}
int mid = (end - start) / 2 + start;
if (array[mid] == k) {
if ((mid > start && array[mid - 1] != k) || mid == start) {
return mid;
} else {
end = mid - 1;
}
} else if (array[mid] > k) {
end = mid - 1;
} else {
start = mid + 1;
}
return getLeftIndex(array, k, start, end);
}
public int getRightIndex(int[] array, int k, int start, int end) {
if (start > end) {
return -1;
}
int mid = (end - start) / 2 + start;
if (array[mid] == k) {
if ((mid < end && array[mid + 1] != k) || mid == end) {
return mid;
} else {
start = mid + 1;
}
} else if (array[mid] < k) {
start = mid + 1;
} else {
end = mid - 1;
}
return getRightIndex(array, k, start, end);
}
面试题40:数组中只出现一次的数字
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路:本题中因为有两个数字都是出现一次,使用与操作后是两个数与的结果,使用结果的一个二进制位为1对原数组进行一个切割。可保证要找的两个数在不同边,且其余相同的值也在同一边。
/**
* 数组中只出现一次的数字
*
* @param array
* @param num1
* @param num2
*/
public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
if (array == null || array.length < 2) {
return;
}
int result = 0;
for (int i : array) {
result ^= i;
}
int index = findIndexOfOne(result);
num1[0] = 0;
num2[0] = 0;
for (int i : array) {
if (isBitOne(i, index)) {
num1[0] ^= i;
} else {
num2[0] ^= i;
}
}
System.out.println("num1: " + num1[0] + " num2: " + num2[0]);
}
public int findIndexOfOne(int n) {
int ret = 0;
while ((n & 1) == 0 && n > 0) {
n >>= 1;
ret++;
}
return ret;
}
public boolean isBitOne(int n, int count) {
n >>= count;
return (n & 1) == 1;
}
面试题41-1:和为S的连续正数序列
题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
/**
* 和为S的连续正数序列
*
* @param sum
* @return
*/
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
if (sum < 3) {
return new ArrayList<ArrayList<Integer>>();
}
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
int mid = (sum + 1) / 2;
int start = 1, end = 2;
list.add(start);
list.add(end);
int count = 3;
while (start < mid) {
if (count > sum) {
count -= start;
start++;
list.remove(0);
} else {
if (count == sum) {
lists.add(new ArrayList<Integer>(list));
}
end++;
count += end;
list.add(end);
}
}
return lists;
}
面试题41-2:和为S的两个数字
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
思路:双指针问题。
/**
* 和为S的两个数字
*
* @param array
* @param sum
* @return
*/
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (array == null || array.length < 2) {
return list;
}
int mul = Integer.MAX_VALUE;
int left = 0, right = array.length - 1;
while (left < right) {
System.out.println("left: " + left + " right: " + right);
int count = array[left] + array[right];
if (count == sum) {
int t = array[left] * array[right];
if (mul > t) {
while (list.size() > 0) {
list.remove(list.size() - 1);
}
list.add(array[left]);
list.add(array[right]);
mul = t;
}
left++;
right--;
} else if (count < sum) {
left++;
} else {
right--;
}
}
return list;
}
面试题42:翻转单词顺序VS左旋转字符串
- 翻转单词顺序
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路:切割字符串,倒叙遍历每个单词,注意的是空字符串和首尾是否有空格。
拼接操作使用StringBuilder!!!
public String ReverseSentence(String str) {
if (str == null || str.trim().equals("")) {
return str;
}
StringBuilder stringBuilder = new StringBuilder();
String[] st = str.split(" ");
for (int i = st.length - 1; i >= 0; i--) {
stringBuilder.append(st[i]);
stringBuilder.append(" ");
}
return stringBuilder.toString().trim();
}
- 左旋转字符串
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路:对字符串操作,在Java中实现比较简单,如果是对数组左选择,可按照书中进行三次旋转。
/**
* 左旋转字符串
*
* @param str
* @param n
* @return
*/
public String LeftRotateString(String str, int n) {
if (str == null || str.equals("") || n <= 0 || n > str.length()) {
return str;
}
int len = str.length();
return str.substring(n, len) + str.substring(0, n);
}
面试题44:扑克牌顺子
题目描述
LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)…他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子…LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
/**
* 扑克牌顺子
*
* @param numbers
* @return
*/
public boolean isContinuous(int[] numbers) {
if (numbers == null || numbers.length < 5) {
return false;
}
Arrays.sort(numbers);
int count0 = 0;
for (int i = 0; i < numbers.length && numbers[i] == 0; i++) {
count0++;
}
int small = count0;
int big = small + 1;
int gap = 0;
while (big < numbers.length) {
if (numbers[small] == numbers[big]) {
return false;
}
// 计算中间差几张牌
gap += (numbers[big] - numbers[small] - 1);
small = big;
big++;
}
return gap > count0 ? false : true;
}
面试题45:孩子们的游戏(圆圈中最后剩下的数)
题目描述
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
思路:说实话,左程云的讲解易懂,推荐阅读!
/**
* 孩子们的游戏(圆圈中最后剩下的数)
*
* @param n
* @param m
* @return
*/
public int LastRemaining_Solution(int n, int m) {
if (n < 1 || m < 1) {
return -1;
}
int last = 0;
for (int i = 2; i <= n; i++) {
last = (last + m) % i;
}
return last;
}
面试题49:把字符串转换成整数
题目描述
将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
- 输入描述:
输入一个字符串,包括数字字母符号,可以为空
- 输出描述:
如果是合法的数值表达则返回该数字,否则返回0
思路:此题主要考察是否考虑到边界的异常情况,如:非法字符,溢出,正负符号。
/**
* 把字符串转换成整数
*
* @param str
* @return
*/
public int StrToInt(String str) {
if (str == null || str.trim().equals("")) {
return 0;
}
char[] ch = str.toCharArray();
int i = 0;
boolean isPositive = true;
if (ch[i] == '-') {
isPositive = false;
i++;
} else if (ch[i] == '+') {
i++;
}
// 使用long存放,防止int型溢出
long ret = 0;
for (; i < ch.length; i++) {
if (ch[i] >= '0' && ch[i] <= '9') {
ret = ret * 10 + (ch[i] - '0');
} else {
return 0;
}
}
ret = isPositive ? ret : -ret;
if (ret <= Integer.MAX_VALUE && ret >= Integer.MIN_VALUE) {
return (int) ret;
}
return 0;
}
面试题52:构建乘积数组
题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。
/**
*
* @param A
* @return
* 时间负责度为n
*/
public int[] multiply(int[] A) {
if (A == null || A.length < 1) {
return A;
}
int[] ret = new int[A.length];
ret[0] = 1; // save 0-(i-1) multiply
for (int i = 1; i < ret.length; i++) {
ret[i] = ret[i - 1] * A[i - 1];
}
int tmp = 1; // save (i+1)-n multiply
for (int i = A.length - 2; i >= 0; i--) {
tmp *= A[i + 1];
ret[i] *= tmp;
}
return ret;
}
面试题54:表示数值的字符串
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路:
数值的字符串模式:
([]之间为可有可无部分)`
/**
* 表示数值的字符串
* @param str
* @return
*/
public boolean isNumeric(char[] str) {
if (str == null || str.length == 0) {
return false;
}
int i = 0;
if (str[i] == '+' || str[i] == '-') {
i++;
}
boolean numeric = true;
i = scanDigits(str, i);
if (i < str.length) {
// for floats
if (str[i] == '.') {
i++;
i = scanDigits(str, i);
if (i < str.length && (str[i] == 'e' || str[i] == 'E')) {
return isExponential(str, i);
}
} else if (str[i] == 'e' || str[i] == 'E') {
// for integers
return isExponential(str, i);
} else {
return false;
}
}
return numeric && i >= str.length;
}
public int scanDigits(char[] str, int i) {
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
i++;
}
return i;
}
public boolean isExponential(char[] str, int i) {
if (str[i] != 'e' && str[i] != 'E') {
return false;
}
i++;
// e | E 后可直接跟随正负号
if (i < str.length && (str[i] == '+' || str[i] == '-')) {
i++;
}
// 以e|E 或者+|- 结尾
if (i >= str.length) {
return false;
}
// 遍历剩下是否都是数字
i = scanDigits(str, i);
// 成立条件为遍历完成
return (i >= str.length) ? true : false;
}
面试题55:字符流中第一个不重复的字符
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:Hash表
/**
* 字符流中第一个不重复的字符
*/
private int[] map = new int[256];
private char once = 'A';
//Insert one char from stringstream
public void Insert(char ch) {
map[ch - 'A']++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
if (once == '#' || map[once] != 1) {
once = '#';
for (int i = 0; i < map.length; i++) {
if (map[i] == 1) {
once = (char) i;
break;
}
}
}
return once;
}
面试题56:链表中环的入口结点
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路
- 类似判断是否有环,先一快一慢指针,判断是否有环,找出环中一个节点;
- 从此节点遍历环,统计环内节点个数n;
- 在从头节点移动一个指定n步,再同时从头部移动一个指针,最后两个指向的同一个节点时,即为入口地址。
这题类似判断链表中是否有环,由于需要找出具体的入口节点,此题难度更大。
/**
* 链表中环的入口结点
* @param pHead
* @return
*/
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null) {
return null;
}
ListNode node = getNodeInCircle(pHead);
if (node == null) {
return null;
}
int countOfCircleNode = 1;
ListNode iter = node.next;
while (iter != node) {
countOfCircleNode++;
iter = iter.next;
}
node = pHead;
iter = pHead;
for (int i = 0; i < countOfCircleNode; i++) {
node = node.next;
}
while (iter != node) {
iter = iter.next;
node = node.next;
}
return iter;
}
public ListNode getNodeInCircle(ListNode head) {
ListNode quick = head;
ListNode slow = head;
while (slow != null && quick != null) {
slow = slow.next;
quick = quick.next;
if (quick != null) {
quick = quick.next;
} else {
return null;
}
if (slow == quick) {
return slow;
}
}
return null;
}
面试题57:删除链表中重复的结点
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:该题与去重的差距,需要删除所有重复节点
- 首先申请一个节点index,将index.next指向头结点pHead;再用一个指针q指向头结点的pHead.next;
- 如果q与index.next不相等,且q==index.next.next,即可判断index.next为不重复节点,index后移,index = index.next;
- 如果q与index.next不相等,但是q!=index.next.next,此时可以判断index.next为重复节点,将index.next指向当前的q,即删除了index到q之间的节点;
- 如果qindex.next,则p q,q继续后移,q=q.next。
- 遍历结束后,如果index.next.next==null;说明index.next节点也为不重复节点,否则需要直接将index.next 指向空。
/**
* 删除链表中重复的结点
*
* @param pHead
* @return
*/
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return pHead;
}
ListNode index = new ListNode(-1);
index.next = pHead;
// 记录最后节点是否为重复节点
ListNode q = pHead.next;
pHead = index;
while (q != null) {
if (q.val != index.next.val) {
if (q == index.next.next)
index = index.next;
else
index.next = q;
}
q = q.next;
}
// 如果非重复节点则相等,需要记录上
if (index.next.next != null)
index.next = null;
return pHead.next;
}
面试题59:对称的二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:同一层次的对称位置两个节点node1.left == node2.right && node1.right==node2.left
/**
* 对称的二叉树
*
* @param pRoot
* @return
*/
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null) {
return true;
}
return justfy(pRoot.left, pRoot.right);
}
public boolean justfy(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
} else if (left == null) {
return false;
} else if (right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
return justfy(left.left, right.right) && justfy(left.right, right.left);
}
面试题61:按之字形顺序打印二叉树
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:层次遍历的一种变种。
/**
* 按之字形顺序打印二叉树
*
* @param pRoot
* @return
*/
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
if (pRoot == null) {
return lists;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(pRoot);
while (stack1.size() > 0 || stack2.size() > 0) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (!stack1.isEmpty()) {
while (!stack1.isEmpty()) {
TreeNode node = stack1.pop();
list.add(node.val);
if (node.left != null) {
stack2.push(node.left);
}
if (node.right != null) {
stack2.push(node.right);
}
}
} else if (!stack2.isEmpty()) {
while (!stack2.isEmpty()) {
TreeNode node = stack2.pop();
list.add(node.val);
if (node.right != null) {
stack1.push(node.right);
}
if (node.left != null) {
stack1.push(node.left);
}
}
}
if (list.size() > 0) {
lists.add(list);
}
}
return lists;
}
面试题60:把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:队列,先进先出,同时记录当前层次节点个数和下一层节点个数。
/**
* 把二叉树打印成多行
*
* @param pRoot
* @return
*/
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
if (pRoot == null) {
return lists;
}
Queue<TreeNode> queue = new ConcurrentLinkedQueue<>();
queue.add(pRoot);
int next = 0;
int cur = 1;
ArrayList<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.add(node.left);
next++;
}
if (node.right != null) {
queue.add(node.right);
next++;
}
cur--;
if (cur == 0) {
cur = next;
next = 0;
if (list.size() > 0) {
lists.add(list);
list = new ArrayList<>();
}
}
}
return lists;
}
面试题63:二叉搜索树的第k个结点
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:搜索二叉树的中序遍历为递增序列。可以考虑是用list存储遍历结果,消耗o(n)空间。书中给出了O(1)空间的解法。
/**
* 二叉搜索树的第k个结点
*
* @param pRoot
* @param k
* @return
*/
int k = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null || k < 1) {
return null;
}
this.k = k;
return searchKth(pRoot);
}
TreeNode searchKth(TreeNode node) {
TreeNode target = null;
if (node.left != null) {
target = searchKth(node.left);
}
if (target == null) {
if (k == 1) {
target = node;
}
k--;
}
if (target == null && node.right != null) {
target = searchKth(node.right);
}
return target;
}
面试题65:滑动窗口的最大值
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
/**
* 滑动窗口的最大值
*
* @param num
* @param size
* @return
*/
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> list = new ArrayList<>();
if (num == null || num.length < size || size < 1) {
return list;
}
Deque<Integer> queue = new ConcurrentLinkedDeque<>();
for (int i = 0; i < size; i++) {
while (!queue.isEmpty() && num[i] >= num[queue.getLast()]) {
queue.pollLast();
}
queue.addLast(i);
}
for (int i = size; i < num.length; i++) {
list.add(num[queue.getFirst()]);
while (!queue.isEmpty() && num[i] >= num[queue.getLast()]) {
queue.pollLast();
}
if (!queue.isEmpty() && queue.getFirst() <= (i - size)) {
queue.pollFirst();
}
queue.addLast(i);
}
list.add(num[queue.getFirst()]);
return list;
}