question:
Implement a method String[] dedup(String[] a) that returns the objects in a[] in sorted order, with duplicates removed.
answer:
//就是先排序,再看相邻是否重复
//我用的优先队列
import edu.princeton.cs.algs4.*; public class Deldumplicates { public static String[] dedup(String[] a) { MinPQ<String> pq = new MinPQ<String>(a); int i = 0; String[] b = new String[a.length]; b[i++] = pq.delMin(); while(!pq.isEmpty()) { String t = pq.delMin(); if(t == b[i-1]) continue; b[i++] = t; } return b; } public static void main(String[] args) { String[] a = {"d", "a", "c", "c", "c", "b"}; String[] b = new String[a.length]; b = dedup(a); int i = 0; while(b[i] != null) { StdOut.print(b[i] + " "); i++; } StdOut.println(); } }