数组中常用算法(方法)总结
1.堆栈
注意堆栈中的node需要暂存哪些数据,以及入口。
举例:二维数组中找到用相邻字母组成的目标字符串。
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
2.动态规划
找路线或最短路径时常常用到,注意第一行和第一列;找最大最小乘积或合时也常用到。
举例1:
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.
举例2:
For example, given the following triangle
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
注意:这道题是从下往上走,一则从下向上可直接得到一个最优解;二则从上到下的话需要判断每行左右两边计算方法和中间不同。
3.两个指针一前以后,满足某个条件则移动某个指针
通常用于排序数组中。
举例:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
4.二叉树深度优先遍历(递归)
有的将参数传递进递归中,有的是在递归中返回结果。
举例:
Subsets I II
注意:subsets I也可以用二进制来做
5.二分法查找元素
注意是while(l<r)还是while(l<=r)
6.两个指针一起走
举例:Remove Duplicates from Sorted Array、Remove Duplicates from Sorted Array II
7.滑动窗口
定义两个指针,右边的先走,左边的再走,知道右边到了尽头或者左边超过了右边。在这个过程中记录一些数据。
举例1:
given the array [2,3,1,2,4,3]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
举例2:(也可以放到动态规划里)
given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
注意:这道题要判断一下前面一段的合是正还是负,如果是整数,则直接加上下一个数;如果是负数,那么sum等于下一个数,也就是开启新的一个窗口。
8.摩尔投票法
跟目标值一样票数加1,不一样票数减1,最后看剩下谁,再验证。
举例:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
9.反向思维法
让你找满足某种规则的数,你就看看如果不存在是什么样子的,然后拿出不符合的情况就是解了。
举例:
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.