比如让你找k个最接近的值,这个k的取值范围一定要注意,如果k >= n,那就没必要再找了。比如让你找第k个最大值或者最小值,那就直接把k = 1和k = n - 1的结果作为base case返回。这样的好处是后面处理会更少bug也会更快一点,尤其是DP题目的时候,有时候你定义dp[] = new int[n],不是小1号的array,最后返回结果是dp[n - 1],那如果输入是长度为0的数组,岂不是Index Out of Bound了。
Index Out of Boud,在while循环并且i++或i--的时候,一定要注意写成while (i < n && A == A[i - 1])和while (i >= 0 && A[i] == A[i + 1]),就是必须要先检查index是否越界。[/i]
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b, a)); // This is to call the Integer function so only works for int and Integer.
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b.compareTo(a));// This is to call the natural order which is implemented by the default Comparable method. Can only be used if there is a default Comparable method.
有时候需要把二维数组的index = [i,j] 写一个class封装进去,但是这样麻烦的是要overwrite hashCode判断2个index是否一样。简单的办法就是把二维数组转换成一维数组的index,这样就不需要新建class也就避免overwrite hashCode了,index = i * n + j,反过来 i = index / n, j = index % n
Java传参只有pass by value。如果是primitive type比如int a= 5,则传入的是这个a 的copy,等于是再copy出一个数5传入函数中,函数执行完根本不改变a的值,一顿操作猛如虎一看战绩零杠五。而如果是Object,则传入的是Object的地址的copy,所以在此地址上作出的改变都改变了Object的内容。