常用算法

36 篇文章 0 订阅


本文整理了一些算法实例,分享给大家,同时也方便自己在需要时进行查找。

1.String/Array/Matrix

在Java中,String是一个包含char数组和其它字段、方法的类。

常用Api如下:

toCharArray() //get char array of a String
Arrays.sort()  //sort an array
Arrays.toString(char[] a) //convert to string
charAt(int x) //get a char at the specific index
length() //string length
length //array size 
substring(int beginIndex) 
substring(int beginIndex, int endIndex)
Integer.valueOf()//string to integer
String.valueOf()/integer to string
String/arrays很容易理解,但与它们有关的问题常常需要高级的算法去解决,例如动态编程、递归等。

下面列出一些需要高级算法才能解决的经典问题:

经典题目:
0) Rotate Array
1) Evaluate Reverse Polish Notation (Stack)
2) Longest Palindromic Substring (DP)
3) Word Break (DP)
3) Word Break II (DP, DFS)
4) Word Ladder (Queue, BFS)
5) Median of Two Sorted Arrays
6) Regular Expression Matching
7) Merge Intervals
8) Insert Interval
9) Two Sum
9) Two Sum II – Input array is sorted
9) Two Sum III - Data structure design
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 [Palantir]
22) Triangle
23) Distinct Subsequences Total
24) Maximum Subarray [Palantir, LinkedIn]
24) Maximum Product Subarray [LinkedIn]
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 [Google]
29) Palindrome Partitioning
29) Palindrome Partitioning II 
30) Reverse Words in a String 
31) Find Minimum in Rotated Sorted Array 
31) Find Minimum in Rotated Sorted Array II
32) Find Peak Element
33) Min Stack
34) Majority Element
35) Combination Sum (DFS)
35) Combination Sum II (DFS)
36) Best Time to Buy and Sell Stock 
36) Best Time to Buy and Sell Stock II
36) Best Time to Buy and Sell Stock III (DP)
36) Best Time to Buy and Sell Stock IV (DP)
37) Longest Common Prefix [Google]
38) Largest Number
39) Combinations (DFS)
40) Compare Version Numbers
41) Gas Station
42) Candy [Google]
43) Jump Game
44) Pascal's Triangle
44) Pascal’s Triangle II 
45) Container With Most Water
46) Count and Say
47) Repeated DNA Sequences
48) House Robber 
49) Dungeon Game (DP) 
50) Number of Islands (DFS/BFS)
51) Surrounded Regions (BFS)
52) Max Points on a Line
53) Letter Combinations of a Phone Number (DFS)
54) Remove Element 
55) Anagrams
56) Search for a Range
57) Simplify Path
58) Isomorphic Strings
59) Minimum Size Subarray Sum
60) Minimum Path Sum (DP)
61) Unique Paths (DP)

2.链表的类实现

在Java中实现链表是非常简单的,每个节点都有一个值,然后把它链接到下一个节点。 

class Node {
	int val;
	Node next;
 
	Node(int x) {
		val = x;
		next = null;
	}
}

链表两个著名的应用是栈Stack和队列Queue。在Java标准库都都有实现,一个是Stack,另一个是LinkedList(Queue是它实现的接口)。

经典题目:

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
10) Intersection of Two Linked Lists
11) Remove Linked List Elements
12) Swap Nodes in Pairs
13) Reverse Linked List

栈(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;
		}	
	}
}

值得一提的是,Java标准库中已经包含一个叫做Stack的类,链表也可以作为一个队列使用(add()和remove())。(链表实现队列接口)如果你在面试过程中,需要用到栈或队列解决问题时,你可以直接使用它们。

在实际中,需要用到链表的算法有:

3.树&堆

这里的树通常是指二叉树。

class TreeNode{
	int value;
	TreeNode left;
	TreeNode right;
} 
下面是一些与二叉树有关的概念:

  • 二叉树搜索:对于所有节点,顺序是:left children <= current node <= right children;
  • 平衡vs.非平衡:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树;
  • 满二叉树:除最后一层无任何子节点外,每一层上的所有结点都有两个子结点;
  • 完美二叉树(Perfect Binary Tree):一个满二叉树,所有叶子都在同一个深度或同一级,并且每个父节点都有两个子节点;
  • 完全二叉树:若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。

堆(Heap)是一个基于树的数据结构,也可以称为优先队列( PriorityQueue),在队列中,调度程序反复提取队列中第一个作业并运行,因而实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。

下面列出一些基于二叉树和堆的算法:

4.图 Graph 

与Graph相关的问题主要集中在深度优先搜索和宽度优先搜索。深度优先搜索非常简单,你可以从根节点开始循环整个邻居节点。下面是一个非常简单的宽度优先搜索例子,核心是用队列去存储节点。

 

  1. public class GraphTest {  
  2.     public static void breathFirstSearch(GraphNode root, int x){  
  3.         if(root.val == x)  
  4.             System.out.println("find in root");  
  5.    
  6.         Queue queue = new Queue();  
  7.         root.visited = true;  
  8.         queue.enqueue(root);  
  9.    
  10.         while(queue.first != null){  
  11.             GraphNode c = (GraphNode) queue.dequeue();  
  12.             for(GraphNode n: c.neighbors){  
  13.    
  14.                 if(!n.visited){  
  15.                     System.out.print(n + " ");  
  16.                     n.visited = true;  
  17.                     if(n.val == x)  
  18.                         System.out.println("Find "+n);  
  19.                     queue.enqueue(n);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  

第一步,定义一个GraphNode

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; 
	}
}

第二步,定义一个队列

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;
		}	
	}
}
第三步,使用队列进行宽度优先搜索

public class GraphTest {
 
	public static void main(String[] args) {
		GraphNode n1 = new GraphNode(1); 
		GraphNode n2 = new GraphNode(2); 
		GraphNode n3 = new GraphNode(3); 
		GraphNode n4 = new GraphNode(4); 
		GraphNode n5 = new GraphNode(5); 
 
		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};
 
		breathFirstSearch(n1, 5);
	}
 
	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: 2 value: 3 value: 5 Find value: 5 
value: 4

实际中,基于Graph需要经常用到的算法:

5.排序算法

不同排序算法的时间复杂度,大家可以到wiki上查看它们的基本思想。

 

BinSort、Radix Sort和CountSort使用了不同的假设,所有,它们不是一般的排序方法。 

下面是这些算法的具体实例,另外,你还可以阅读: Java开发者在实际操作中是如何排序的

6.递归和迭代

下面通过一个例子来说明什么是递归。

问题:

这里有n个台阶,每次能爬1或2节,请问有多少种爬法?

步骤1:查找n和n-1之间的关系

为了获得n,这里有两种方法:一个是从第一节台阶到n-1或者从2到n-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){
	if(n <= 2) return n;
	int x = f(n-1) + f(n-2);
	return x;
}

递归方法的时间复杂度指数为n,这里会有很多冗余计算。

f(5)
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(2) + f(2) + f(1)
该递归可以很简单地转换为迭代。 

public static int f(int n) {
 
	if (n <= 2){
		return n;
	}
 
	int first = 1, second = 2;
	int third = 0;
 
	for (int i = 3; i <= n; i++) {
		third = first + second;
		first = second;
		second = third;
	}
 
	return third;
}

在这个例子中,迭代花费的时间要少些。关于迭代和递归,你可以去 这里看看。

7.动态规划算法

动态规划主要用来解决如下技术问题:

  • 通过较小的子例来解决一个实例;
  • 对于一个较小的实例,可能需要许多个解决方案;
  • 把较小实例的解决方案存储在一个表中,一旦遇上,就很容易解决;
  • 附加空间用来节省时间。

上面所列的爬台阶问题完全符合这四个属性,因此,可以使用动态规划来解决: 

public static int[] A = new int[100];
 
public static int f3(int n) {
	if (n <= 2)
		A[n]= n;
 
	if(A[n] > 0)
		return A[n];
	else
		A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!
	return A[n];
}

一些基于动态规划的算法:

8.按位操作符

位操作符:


从一个给定的数n中找位i(i从0开始,然后向右开始)

public static boolean getBit(int num, int i){
	int result = num & (1<<i);
 
	if(result == 0){
		return false;
	}else{
		return true;
	}
}

例如,获取10的第二位:

i=1, n=10
1<<1= 10
1010&10=10
10 is not 0, so return true;
典型的位算法:

9.组合和排列

组合和排列的主要差别在于顺序是否重要。

例1:

1、2、3、4、5这5个数字,输出不同的顺序,其中4不可以排在第三位,3和5不能相邻,请问有多少种组合?

例2:

有5个香蕉、4个梨、3个苹果,假设每种水果都是一样的,请问有多少种不同的组合?

基于它们的一些常见算法


本文参考了CSDN上的其他文章,整理出来一个比较全面的,分享给大家。希望对大家在开发过程中有用。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值