1. 重写Arrays.sort
Arrays.sort默认按升序进行排序。降序排列需要自己实现Comparator接口。而且有时候有两个坐标的时候的排序,也需要实现Comparator接口。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public static void main(String[] args) { class point { private int x; private int y; public point(int x, int y) { this.x = x; this.y = y; } } point[] points = new point[5]; Double d; int r_x, r_y; for (int i = 0 ; i < 5; i++) { d = Math.random(); r_x = (int)(d * 10); d = Math.random(); r_y = (int)(d * 10); points[i] = new point(r_x, r_y); } Arrays.sort(points, new Comparator<point>() { @Override public int compare(point o1, point o2) { if (o1.x == o2.x) return o2.y - o1.y; //按y降序排列 return o1.x - o2.x; //按x升序排列 } }); for (point p : points) System.out.println("[" + p.x +"," + p.y + "]"); int[][] nums = {{4,3},{2,7},{8,1}}; Arrays.sort(nums, new Comparator<int []>() { public int compare(int[] a, int[] b) { if (a[0] == b[0]) return a[1] - b[1]; else return a[0] - b[0]; } });
2.对容器进行排序:
Collections.sort(S);
Arrays.sort() //默认降序排序
Arrays.sort(T[], Collections.reversOrder()) //升序
Arrays.sort(T[], (a, b) -> a - b);
Arrays.sort(T[], java.util.Comparator) //自己写类实现comparator接口
3. queue的使用
Queue<String> queue = new LinkedList<String>();
- priority queue的使用:
建立大顶堆:
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2; //生成最大堆使用o2-o1,生成最小堆使用o1-o2
}
};
PriorityQueue<Integer> pq = new PriorityQueue<>(k, comparator);
- priority queue中为HashMap元素,怎么根据map的value进行排序?生成小顶堆:
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
(a,b) -> a.getValue()==b.getValue() ? a.getKey().compareTo(b.getKey()) : a.getValue()-b.getValue() );
4.输出数组:
System.out.println(Arrays.toString(nums));
5.int string的相互转换
int to string: String x = Integer.toString(x);
string to int: int x = Integer.parseInt(x);
6.快排模版(死记都要记住!)(以及二叉树中序、后序非递归遍历模版)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public static void quickSort(int[] nums) { recurpartition(nums, 0, nums.length - 1); } private static void recurpartition(int[] nums, int low, int high) { if (high - 1 < low || low >= high) return; int part = partArray(nums, low, high); recurpartition(nums, low, part - 1); recurpartition(nums, part + 1, high); } private static int partArray(int[] nums, int low, int high) { int pivot = nums[low]; while (low < high) { while (low < high && nums[high] > pivot) high--; nums[low] = nums[high]; while (low < high && nums[low] < pivot) low++; nums[high] = nums[low]; } nums[low] = pivot; return low; }
7. Java中:
- 1.length()方法是针对字符串来说的,要求一个字符串的长度就要用到它的length()方法;
- 2.length属性是针对Java中的数组来说的,要求数组的长度可以用其length属性;
- 3.java中的size()方法是针对泛型集合说的,如果想看这个泛型有多少个元素,就调用此方法来查看!