面试10大算法汇总+常见题目解答(Java)
原文地址:http://www.lilongdream.com/2014/04/10/94.html(为转载+整理)
以下从Java的角度总结了面试常见的算法和数据结构:字符串,链表,树,图,排序,递归 vs. 迭代,动态规划,位操作,概率问题,排列组合,以及一些需要寻找规律的题目。
1. 字符串、数组和矩阵
首先需要注意的是和C++不同,Java字符串不是char数组。没有IDE代码自动补全功能,应该记住下面这些常用的方法。
- toCharArray() //获得字符串对应的char数组
- Arrays.sort() //数组排序
- Arrays.toString(char[] a) //数组转成字符串
- charAt(int x) //获得某个索引处的字符
- length() //字符串长度
- length //数组大小
- substring(int beginIndex)
- substring(int beginIndex, int endIndex)
- Integer.valueOf() //string to integer
- String.valueOf() //integer to string
字符串和数组本身很简单,但是相关的题目需要更复杂的算法来解决。比如说动态规划,搜索等。
经典题目:
1) Evaluate Reverse Polish Notation
2) Longest Palindromic Substring
3) Word Break
4) Word Ladder
5) Median of Two Sorted Arrays
6) Regular Expression Matching
7) Merge Intervals
8) Insert Interval
9) Two Sum
9) 3Sum
9) 4Sum
10) 3Sum Closest
11) String to Integer
12) Merge Sorted Array
13) Valid Parentheses
14) Implement strStr()
15) Set Matrix Zeroes
16) Search Insert Position
17) Longest Consecutive Sequence
18) Valid Palindrome
19) Spiral Matrix
20) Search a 2D Matrix
21) Rotate Image
22) Triangle
23) Distinct Subsequences Total
24) Maximum Subarray
25) Remove Duplicates from Sorted Array
26) Remove Duplicates from Sorted Array II
27) Longest Substring Without Repeating Characters
28) Longest Substring that contains 2 unique characters
29) Palindrome Partitioning
2. 链表
在Java中,链表的实现非常简单,每个节点Node都有一个值val和指向下个节点的链接next。
- class Node {
- int val;
- Node next;
- Node(int x) {
- val = x;
- next = null;
- }
- }
链表两个著名的应用是栈Stack和队列Queue。在Java标准库中都有实现,一个是Stack,另一个是LinkedList(Queue是它实现的接口)。
Stack
- class Stack{
- Node top;
- public Node peek(){
- if(top != null){
- return top;
- }
- return null;
- }
- public Node pop(){
- if(top == null){
- return null;
- }else{
- Node temp = new Node(top.val);
- top = top.next;
- return temp;
- }
- }
- public void push(Node n){
- if(n != null){
- n.next = top;
- top = n;
- }
- }
- }
Queue
- class Queue{
- Node first, last;
- public void enqueue(Node n){
- if(first == null){
- first = n;
- last = first;
- }else{
- last.next = n;
- last = n;
- }
- }
- public Node dequeue(){
- if(first == null){
- return null;
- }else{
- Node temp = new Node(first.val);
- first = first.next;
- return temp;
- }
- }
- }
经典题目:
1) Add Two Numbers
2) Reorder List
3) Linked List Cycle
4) Copy List with Random Pointer
5) Merge Two Sorted Lists
6) Merge k Sorted Lists *
7) Remove Duplicates from Sorted List
8) Partition List
9) LRU Cache
3. 树和堆
这里的树通常是指二叉树,每个节点都包含一个左孩子节点和右孩子节点,如下所示:
- class TreeNode{
- int value;
- TreeNode left;
- TreeNode right;
- }
下面是与树相关的一些概念:
二叉搜索树:左结点 <= 中结点 <= 右结点
平衡 vs. 非平衡:平衡二叉树中,每个节点的左右子树的深度相差至多为1(1或0)。
满二叉树(Full Binary Tree):除叶子节点以外的每个节点都有两个孩子。
完美二叉树(Perfect Binary Tree):是具有下列性质的满二叉树:所有的叶子节点都有相同的深度或处在同一层次,且每个父节点都必须有两个孩子。
完全二叉树(Complete Binary Tree):二叉树中,可能除了最后一层,每一层都被完全填满,且所有节点都必须尽可能向左靠。
堆是一种特殊的基于树的数据结构,满足堆属性。其操作的时间复杂度是很重要的(例如查找最小,删除最小,插入等)。在Java中,知道PriorityQueue很重要。
经典题目:
1) Binary Tree Preorder Traversal
2) Binary Tree Inorder Traversal
3) Binary Tree Postorder Traversal
4) Word Ladder
5) Validate Binary Search Tree
6) Flatten Binary Tree to Linked List
7) Path Sum
8) Construct Binary Tree from Inorder and Postorder Traversal
9) Convert Sorted Array to Binary Search Tree
10) Convert Sorted List to Binary Search Tree
11) Minimum Depth of Binary Tree
12) Binary Tree Maximum Path Sum *
13) Balanced Binary Tree
4. 图
图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。深度优先搜索很简单,广度优先要注意使用queue存储节点。下面是一个简单的用队列Queue实现的广度优先搜索。
1) 定义图节点
- class GraphNode{
- int val;
- GraphNode next;
- GraphNode[] neighbors;
- boolean visited;
- GraphNode(int x) {
- val = x;
- }
- GraphNode(int x, GraphNode[] n){
- val = x;
- neighbors = n;
- }
- public String toString(){
- return "value: "+ this.val;
- }
- }
2) 定义Queue
- class Queue{
- GraphNode first, last;
- public void enqueue(GraphNode n){
- if(first == null){
- first = n;
- last = first;
- }else{
- last.next = n;
- last = n;
- }
- }
- public GraphNode dequeue(){
- if(first == null){
- return null;
- }else{
- GraphNode temp = new GraphNode(first.val,
- first.neighbors);
- first = first.next;
- return temp;
- }
- }
- }
3) 使用Queue的BFS
- public class GraphTest {
- public static void main(String[] args) {
- );
- );
- );
- );
- );
- n1.neighbors = new GraphNode[]{n2,n3,n5};
- n2.neighbors = new GraphNode[]{n1,n4};
- n3.neighbors = new GraphNode[]{n1,n4,n5};
- n4.neighbors = new GraphNode[]{n2,n3,n5};
- n5.neighbors = new GraphNode[]{n1,n3,n4};
- );
- }
- public static void breathFirstSearch(GraphNode root, int x){
- if(root.val == x)
- System.out.println("find in root");
- Queue queue = new Queue();
- root.visited = true;
- queue.enqueue(root);
- while(queue.first != null){
- GraphNode c = (GraphNode) queue.dequeue();
- for(GraphNode n: c.neighbors){
- if(!n.visited){
- System.out.print(n + " ");
- n.visited = true;
- if(n.val == x)
- System.out.println("Find "+n);
- queue.enqueue(n);
- }
- }
- }
- }
- }
输出:
value: 4
经典题目:复制图(Clone Graph)
5. 排序
下面是不同排序算法的时间复杂度,你可以去维基上看一下这些算法的基本思想。
算法 | 平均时间复杂度 | 最坏时间复杂度 | 辅助空间 |
冒泡排序(Bubble sort) | n^2 | n^2 | 1 |
选择排序(Selection sort) | n^2 | n^2 | 1 |
插入排序(Insertion sort) | n^2 | n^2 | |
快速排序(Quick sort) | n log(n) | n^2 | |
归并排序(Merge sort) | n log(n) | n log(n) | depends |
* 另外还有BinSort, RadixSort和CountSort 三种比较特殊的排序。
(此处可见我的整理:http://www.lilongdream.com/2014/04/10/83.html)
你可能想看看 how developers sort inJava 。
经典题目:Mergesort, Quicksort, InsertionSort.
6. 递归 vs. 迭代
对程序员来说,递归应该是一个与生俱来的思想(a built-in thought),可以通过一个简单的例子来说明。
问题:
有n步台阶,一次只能上1步或2步,共有多少种走法。
步骤1:找到走完前n步台阶和前n-1步台阶之间的关系。
为了走完n步台阶,只有两种方法:从n-1步台阶爬1步走到或从n-2步台阶处爬2步走到。如果f(n)是爬到第n步台阶的方法数,那么f(n) = f(n-1) + f(n-2)。
步骤2:确保开始条件是正确的。
f(0) = 0;
f(1) = 1;
- public static int f(int n){
- ) return n;
- );
- return x;
- }
递归方法的时间复杂度是指数级的,因为有很多冗余的计算:
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
f(1) + f(0) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
直接的想法是将递归转换为迭代:
- public static int f(int n) {
- ){
- return n;
- }
- ;
- ;
- ; i <= n; i++) {
- third = first + second;
- first = second;
- second = third;
- }
- return third;
- }
这个例子迭代花费的时间更少,你可能想看看两者的区别 Recursion vs Iteration。
7. 动态规划
动态规划是解决具有下面这些性质问题的技术:
- 一个问题可以通过解决更小子问题来解决,或者说问题的最优解包含了其子问题的最优解
- 有些子问题的解可能需要计算多次
- 子问题的解存储在一张表格里,这样每个子问题只需计算一次
- 需要额外的空间以节省时间
爬台阶问题完全符合上面的四条性质,因此可以用动态规划法来解决。
- ];
- public static int f3(int n) {
- )
- A[n]= n;
- )
- return A[n];
- else
- ); //存储结果,只计算一次!
- return A[n];
- }
经典题目:
1) Edit Distance
2)
Longest Palindromic Substring
3) Word Break
4) Maximum Subarray
8. 位操作
常用位操作符:
OR (|) | AND (&) | XOR (^) | Left Shift (<<) | Right Shift (>>) | Not (~) |
1|0=1 | 1&0=0 | 1^0=1 | 0010<<2=1000 | 1100>>2=0011 | ~1=0 |
用一个题目来理解这些操作:获得给定数字n的第i位:(i从0计数并从右边开始)
- public static boolean getBit(int num, int i){
- <<i);
- ){
- return false;
- }else{
- return true;
- }
例如,获得数字10的第2位:
1<<1= 10
1010&10=10
10 is not 0, so return true;
9. 概率问题
解决概率相关的问题通常需要先分析问题,下面是一个简单的例子:
一个房间里有50个人,那么至少有两个人生日相同的概率是多少?(忽略闰年的事实,也就是一年365天)
计算某些事情的概率很多时候都可以转换成先计算其相对面。在这个例子里,我们可以计算所有人生日都互不相同的概率,也就是:365/365 * 364/365 * 363/365 * … * (365-49)/365,这样至少两个人生日相同的概率就是1 – 这个值。
- public static double caculateProbability(int n){
- ;
- ; i<n; i++){
- x *= (365.0-i)/365.0;
- }
- );
- ;
- }
经典题目:桶中取球
10. 排列组合
组合和排列的区别在于次序是否关键。
例1:
1、2、3、4、5这5个数字,用java写一个方法,打印出所有不同的排列, 如:51234、41235等。要求:"4″不能在第三位,"3″与”5″不能相连。
例2:
5个香蕉,4个梨子,3个苹果。同一种水果都是一样的,这些水果有多少种不同的组合情况。
经典问题:
1) Permutations
2) Permutations II
3) Permutation Sequence
11. 其他类型的题目
主要是不能归到上面10大类的。需要寻找规律,然后解决问题。
经典题目:
1) Reverse Integer
2) Palindrome Number
3) Pow(x,n)
4) Subsets
5) Subsets II
参考/推荐的资料:
1. Binary tree
2. Introduction to Dynamic Programming
3. UTSA Dynamic Programming slides
4. Birthday paradox
5. Cracking the Coding Interview: 150 Programming InterviewQuestions and Solutions, Gayle Laakmann McDowell
6. Counting sort
7. LeetCode Online Judge
面试10大算法汇总+常见题目解答(Java)的更多相关文章
- 面试10大算法汇总——Java篇
问题导读 1 字符串和数组 2 链表 3 树 4 图 5 排序 6 递归 vs 迭代 7 动态规划 8 位操作 9 概率问题 10 排列组合 11 其他 -- 寻找规律 英文版 以下从Java角度解释 ...
- 数据挖掘10大算法(1)——PageRank
1. 前言 这系列的文章主要讲述2006年评出的数据挖掘10大算法(见图1).文章的重点将偏向于算法的来源以及算法的主要思想,不涉及具体的实现.如果发现文中有错,希望各位指出来,一起讨论. 图1 来自 ...
- 数据结构笔记01:编程面试过程中常见的10大算法(java)
以下是在编程面试中排名前10的算法相关的概念,我会通过一些简单的例子来阐述这些概念.由于完全掌握这些概念需要更多的努力,因此这份列表只是作为一个介绍.本文将从Java的角度看问题,包含下面的这些概念: ...
- Java面试常被问到的题目+解答
第一,anonymousinnerclass(匿名内部类)是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)? 不行,对于匿名内部类,看到的一句话说的 ...
- 面试必备:排序算法汇总(c++实现)
排序算法主要考点: 7种排序 冒泡排序.选择排序.插入排序.shell排序.堆排序.快速排序.归并排序 以上排序算法是面试官经常会问到的算法,至于其他排序比如基数排序等等,这里不列举. 以下算法通过c ...
- JavaScript实现10大算法可视化
参考博客: https://www.cnblogs.com/Unknw/p/6346681.html#4195503 十大经典算法 一张图概括: 名词解释: n:数据规模 k:“桶”的个数 In-pl ...
- python 10大算法之二 LogisticRegression 笔记
使用的包 import matplotlib.pyplot as plt import pandas as pd import numpy as npfrom sklearn import datas ...
- python 10大算法之一 LinearRegression 笔记
简单的线性回归预测房价 #!/usr/bin/env python # encoding: utf-8 """ @version: @author: --*--. @fi ...
- LeetCode算法题目解答汇总(转自四火的唠叨)
LeetCode算法题目解答汇总 本文转自<四火的唠叨> 只要不是特别忙或者特别不方便,最近一直保持着每天做几道算法题的规律,到后来随着难度的增加,每天做的题目越来越少.我的初衷就是练习, ...
随机推荐
- C++ Primer Plus的若干收获--(二)
哎,真是不想吐槽考驾照的艰辛历程了.跑到大西郊,顶着大太阳,一天就能摸上个十几分钟二十分钟的车,简直不要太坑爹,这两天真是做的我屁股疼的不行. .. 今天果断不去了.仅仅可惜我的大阿根廷啊,坚持到最后 ...
- SpringCloud系列十五:使用Hystrix实现容错
1. 回顾 上文讲解了容错的重要性,以及容错需要实现的功能. 本文来讲解使用Hystrix实现容错. 2. Hystrix简介 Hystrix是Netflix开源的一个延迟和容错库,用于隔离访问远程系 ...
- Yum Error Another app is currently holding the yum lock; waiting for it to exit
Another app is currently holding the yum lock; waiting for it to exit... The other application is: P ...
- Shell脚本与vi编辑器:vi启动与退出、工作模式、命令大全
Vi简介 Vi是一种广泛存在于各种UNIX和Linux系统中的文本编辑程序. Vi不是排版程序,只是一个纯粹的文本编辑程序. Vi是全屏幕文本编辑器,它没有菜单,只有命令. Vi不是基于窗口的,所以, ...
- awk 数组
Arrays Arrays are subscripted with an expression between square brackets ([ and ]). If the ...
- 李洪强经典面试题41-iOS选择题
1.及时聊天app不会采用的网络传输方式是 DA UDP B TCP C Http D FTP 2.下列技术不属于多线程的是 AA Block B NSThread C NSOperation D G ...
- UITabelViewFootView(转)
在处理UITableView表格时,我们希望在View底部添加按钮. 用户拖动UITableView时按钮能跟随移动. 如题,实现如下界面: - (CGFloat)tableView:(UITable ...
- 也许,这样理解HTTPS更容易_转载
转自:也许,这样理解HTTPS更容易 原文衔接:https://showme.codes/2017-02-20/understand-https/ 作者:翟志军 摘要 本文尝试一步步还原HTTPS的 ...
- Spring MVC参数方法名称解析器
以下示例显示如何使用Spring Web MVC框架来实现多动作控制器的参数方法名称解析器. MultiActionController类可在单个控制器中分别映射多个URL到对应的方法. 所下所示配置 ...
- ios - UINavigationBar添加背景图片的几种简单思路
UITabBarController下面常常需要为多个ViewController设置导航栏样式,总结了一下遇到过的为UINavigationBar添加背景图片的几种简单思路 以设置背景图片为例: 第 ...