LeetCode - Algorithms - 547. Friend Circles

Problem

547. Friend Circles

Java

union–find

© 1.5 Case Study: Union-Find Copyright © 2000–2019 Robert Sedgewick and Kevin Wayne. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public int findCircleNum(int[][] M) {
int N = M.length;
UF uf = new UF(N);
for(int i=0; i<N; i++) {
for(int j=0; j<i; j++) {
if (M[i][j]==1)
uf.union(i,j);
}
}
return uf.count();
}
}

/**
* Weighted quick-union by rank with path compression by halving.
* @author Robert Sedgewick
* @author Kevin Wayne
* Algorithms, 4th edition textbook code and libraries
* https://github.com/kevin-wayne/algs4
*/
class UF {
private int[] parent;
private byte[] rank;
private int count;

public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}

public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}

public int count() {
return count;
}

public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;

if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}

private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
}

Submission Detail

  • 113 / 113 test cases passed.
  • Runtime: 1 ms, faster than 72.63% of Java online submissions for Friend Circles.
  • Memory Usage: 40.3 MB, less than 68.00% of Java online submissions for Friend Circles.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public int findCircleNum(int[][] M) {
int N = M.length;
List<Edge> edges = new ArrayList<Edge>();
for(int i=0; i<N; i++) {
for(int j=0; j<i; j++) {
if (M[i][j]==1) {
edges.add( new Edge(i,j) );
edges.add( new Edge(j,i) );
}
}
}
Graph graph = new Graph(edges, N);
boolean[] visited = new boolean[N];
for(int i=0; i<N; i++)
visited[i] = false;
int c = 0;
for(int i=0; i<N; i++) {
if (!visited[i]) {
dfs(graph, i, visited);
c++;
}
}

return c;
}

private void dfs(Graph graph, int v, boolean[] visited) {
visited[v] = true;
for (int u : graph.adjList.get(v)) {
if (!visited[u])
dfs(graph, u, visited);
}
}
}

class Edge {
int source, dest;

public Edge(int source, int dest) {
this.source = source;
this.dest = dest;
}
}

class Graph {
List<List<Integer>> adjList = null;

Graph(List<Edge> edges, int N) {
adjList = new ArrayList<>(N);

for (int i = 0; i < N; i++) {
adjList.add(i, new ArrayList<>());
}

for (Edge edge : edges) {
adjList.get(edge.source).add(edge.dest);
}
}
}

Submission Detail

  • 113 / 113 test cases passed.
  • Runtime: 4 ms, faster than 25.38% of Java online submissions for Friend Circles.
  • Memory Usage: 40.1 MB, less than 72.00% of Java online submissions for Friend Circles.

Resources

LeetCode - Algorithms - 867. Transpose Matrix

Problem

867. Transpose Matrix

Given a matrix A, return the transpose of A.

\( \begin{bmatrix}
1 &2 &3 \\
4 &5 &6 \\
7 &8 &9
\end{bmatrix} \Rightarrow \begin{bmatrix}
1 &4 &7 \\
2 &5 &8 \\
3 &6 &9
\end{bmatrix} \)

Java

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[][] transpose(int[][] A) {
int h = A.length;
int w = A[0].length;
int[][] B = new int[w][h];
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++)
B[j][i]=A[i][j];
}
return B;
}
}

Submission Detail

  • 36 / 36 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Transpose Matrix.
  • Memory Usage: 40.6 MB, less than 91.67% of Java online submissions for Transpose Matrix.

A Response to "Bell's Conjecture"

\(\huge e^{i\pi}+1=0 \)

by Charlie Marion and William Dunham

Before we let you get away,
Your choices set in stone,
Consider what we have to say:
E.T.! O, please! Call home!

Stop the presses! Hold that thought!
And listen to our voices.
Ruffled, even overwrought,
We’ll supplement your choices.

Old Archie, Isaac, C. F. Gauss–
Though each deserves a floor
In mathematics’ honored house,
Make room for just one more.

Without the Bard of Basel, Bell,
You’ve clearly dropped the ball.
Our votes are cast for Euler, L.
Whose OPERA says it all:

Six dozen volumes — what a feat!
Profound and deep throughout
Does Leonhard rank with the elite?
Of this there is no doubt.

Consider how he summed, in turn
The quite elusive mix
Of one slash n all squared — you’ll learn
he got π2 slash six.

\( \zeta(2)=\sum_{n=1}^{\infty}\frac{1}{n^2} = \lim_{n \to \infty} (\frac{1}{1^2}+\frac{1}{2^2}+\frac{1}{3^2}+\cdots+\frac{1}{n^2}) = \frac{\pi^2}{6} \)

We’re shocked we did not see his name
With those you justly sainted.
No Euler in your Hall of Fame?
Your judgment’s surely Taine-ted.

It’s time to honor one you missed,
To do your duty well.
Add worthy Euler to your list,
And save him by the Bell.

Euler portrait on the sixth series of the 10 Franc banknote


Tower of Hanoi

Problem

We are given a tower of n disks, initially stacked in decreasing size on one of three pegs: The objective is to transfer the entire tower to one of the other pegs, moving only one disk at a time and never moving a larger one onto a smaller.

Solution

The minimal number of moves required to solve a Tower of Hanoi puzzle is \( 2^n-1 \), where n is the number of disks. This is precisely the nth Mersenne number.

recurrence relation

\( T_0=0, T_1=1 \)
\( T_n=2T_{n-1}+1 \)

if we let \( u_n=T_n+1 \), we have
\( u_0=1 \)
\( u_n=2u_{n-1} \), for n>0
\( u_n=2^n \)
hence \( T_n=2^n-1 \)

Java

recurrence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class HanoiTower {

public static void move(int n, char source, char target, char auxiliary) {
if (n==1)
System.out.println("move " + source + " to " + target);
else {
// Move n - 1 disks from source to auxiliary, so they are out of the way
move(n-1,source,auxiliary,target);
// Move the nth disk from source to target
System.out.println("move " + source + " to " + target);
// Move the n - 1 disks that we left on auxiliary onto target
move(n-1,auxiliary,target,source);
}
}

public static void main(String[] args) {
move(3, 'A', 'C', 'B');
}
}

resources

Why should you listen to Vivaldi's "Four Seasons"? - Betsy Schwarm - TED-Ed

Light, bright, and cheerful. It’s some of the most familiar of all early 18th century music. It’s been featured in uncounted films and television commercials, but what is it and why does it sound that way?

This is the opening of “Spring” from “The Four Seasons,” by Italian composer Antonio Vivaldi. “The Four Seasons” are famous in part because they are a delight to the ear. However, even more notable is the fact that they have stories to tell. At the time of their publication in Amsterdam in 1725, they were accompanied by poems describing exactly what feature of that season Vivaldi intended to capture in musical terms. In providing specific plot content for instrumental music, Vivaldi was generations ahead of his time.

If one were to read the poems simultaneously to hearing the music, one would find the poetic scenes synchronizing nicely with the musical imagery. We are told that the birds welcome spring with happy song, and here they are doing exactly that. Soon, however, a thunderstorm breaks out. Not only is there musical thunder and lightning, there are also more birds, wet, frightened, and unhappy.

In “Summer,” the turtle dove sings her name “tortorella” in Italian, before a hail storm flattens the fields. “Autumn” brings eager hunters dashing out in pursuit of their prey.

The “Winter” concerto begins with teeth chattering in the cold before one takes refuge by a crackling fire. Then it’s back out into the storm where there’ll be slips and falls on the ice. In these first weeks of winter, the old year is coming to a close, and so does Vivaldi’s musical exploration of the seasons.

Not until the early 19th century would such expressive instrumental program music, as it was known, become popular. By then, larger, more varied ensembles were the rule with woodwinds, brass, and percussion to help tell the tale. But Vivaldi pulled it off with just one violin, strings, and a harpsichord. Unlike his contemporary Bach, Vivaldi wasn’t much interested in complicated fugues. He preferred to offer readily accessible entertainment to his listeners with melodies that pop back up later in a piece to remind us of where we’ve been. So the first movement of the “Spring” concerto begins with a theme for spring and ends with it, too, slightly varied from when it was last heard.

It was an inspired way to attract listeners, and Vivaldi, considered one of the most electrifying violinists of the early 18th century, understood the value of attracting audiences. Such concerts might feature himself as the star violinist. Others presented the young musicians of the Pietà, a Venetian girls’ school where Vivaldi was Director of Music. Most of the students were orphans. Music training was intended not only as social skills suitable for young ladies but also as potential careers for those who might fail to make good marriages.

Even in the composer’s own time, Vivaldi’s music served as diversion for all, not just for the wealthy aristocrats. 300 years later, it’s an approach that still works, and Vivaldi’s music still sounds like trotting horses on the move.

The Four Seasons - Sonnet text - Antonio Vivaldi

The Four Seasons is Vivaldi‘s best-known work, and is among the most popular pieces in the classical music repertoire.

Antonio Vivaldi composed a collection of “sound-pictures” that magically brought seasonal sights and sounds to the ear.

Spring

Allegro

Springtime is upon us.
The birds celebrate her return with festive song,
and murmuring streams are
softly caressed by the breezes.
Thunderstorms, those heralds of Spring, roar,
casting their dark mantle over heaven,
Then they die away to silence,
and the birds take up their charming songs once more.

Largo e pianissimo sempre

On the flower-strewn meadow, with leafy branches
rustling overhead, the goat-herd sleeps,
his faithful dog beside him.

Allegro pastorale

Led by the festive sound of rustic bagpipes,
nymphs and shepherds lightly dance
beneath the brilliant canopy of spring.

Summer

Allegro non molto

Under a hard season, fired up by the sun
Languishes man, languishes the flock and burns the pine
We hear the cuckoo’s voice;
then sweet songs of the turtledove and finch are heard.
Soft breezes stir the air, but threatening
the North Wind sweeps them suddenly aside.
The shepherd trembles,
fearing violent storms and his fate.

Adagio e piano – Presto e forte

The fear of lightning and fierce thunder
Robs his tired limbs of rest
As gnats and flies buzz furiously around.

Presto

Alas, his fears were justified
The Heavens thunder and roar and with hail
Cut the head off the wheat and damages the grain.

Autumn

Allegro

Celebrates the peasant, with songs and dances,
The pleasure of a bountiful harvest.
And fired up by Bacchus’ liquor,
many end their revelry in sleep.

Adagio molto

Everyone is made to forget their cares and to sing and dance
By the air which is tempered with pleasure
And (by) the season that invites so many, many
Out of their sweetest slumber to fine enjoyment

Allegro

The hunters emerge at the new dawn,
And with horns and dogs and guns depart upon their hunting
The beast flees and they follow its trail;
Terrified and tired of the great noise
Of guns and dogs, the beast, wounded, threatens
Languidly to flee, but harried, dies.

Winter

Allegro non molto

To tremble from cold in the icy snow,
In the harsh breath of a horrid wind;
To run, stamping one’s feet every moment,
Our teeth chattering in the extreme cold

Largo

Before the fire to pass peaceful,
Contented days while the rain outside pours down.

Allegro

We tread the icy path slowly and cautiously,
for fear of tripping and falling.
Then turn abruptly, slip, crash on the ground and,
rising, hasten on across the ice lest it cracks up.
We feel the chill north winds course through the home
despite the locked and bolted doors…
this is winter, which nonetheless
brings its own delights.

数学题 - 1

A course of pure mathematics, G.H.Hardy

P34

chapterⅠ Real Variables

  1. If a,b,c are positive,and \( a+b+c=1 \),then
    \( (\frac{1}{a}-1)(\frac{1}{b}-1)(\frac{1}{c}-1) \geq 8. \) (Math. Trip. 1932)

if a>0 and b>0 then \( \frac{a+b}{2} \geq \sqrt{ab} \)

\( a>0, b>0, c>0, a+b+c=1 \)

\( (\frac{1}{a}-1)(\frac{1}{b}-1)(\frac{1}{c}-1) \)

\(=\frac{b+c}{a} \times \frac{a+c}{b} \times \frac{a+b}{c} \)

\( \geq 2 \times \frac{\sqrt{bc}}{a} \times 2 \times \frac{\sqrt{ac}}{b} \times 2 \times \frac{\sqrt{ab}}{c} = 8 \)

求极限

p207, No.5

\( \lim_{x \to \infty} \sqrt{x}(\sqrt{x+a}-\sqrt{x}) \)

p207, No.8

\( \lim_{x \to \infty} x^3(\sqrt{x^2+\sqrt{x^4+1}}-x \sqrt{2}) \)

求原函数

p281, No.53

\( \int \frac{x-1}{(x+1) \sqrt{x(x^2+x+1)}}dx \)

p263, No.6

\( \int \frac{1}{x \sqrt{3x^2+2x+1}}dx \)

有理数跟自然数等势

\( NXN \sim N \)

笛卡儿坐标系第一象限内的整数格点是直观地能一笔画联起来的,我是用y=-x的平行线簇,从原点出发,呈锯齿状把所有整数格子点串起来,这就表明NXN的元素是可以线性化的,即能存储到一个数组里

具体的双射关系是:

\( f(\langle a, b \rangle)=\frac{(a+b)(a+b+1)}{2}+b \)

反函数 \( g(a)=\langle \frac{1}{2N(N+3)}-a, a-\frac{1}{2N(N+1)} \rangle \) ,其中 \( N=floor(\frac{\sqrt{8a+1}-1}{2}) \)

是把横纵坐标联立后解一个一元二次方程得的这个结果

LeetCode - Algorithms - 815. Bus Routes

Hard problem. Accepted after four submissions. Done by myself.

Problem

815. Bus Routes

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Solution {
public boolean routesIntersect(int[] route1, int[] route2) {
boolean r = false;
Set<Integer> tmpSet = new HashSet<Integer>();
for(int i=0; i<route1.length; i++)
tmpSet.add(route1[i]);
for(int i=0; i<route2.length; i++) {
if (tmpSet.contains(route2[i])) {
r = true;
break;
}
}
return r;
}

public boolean inArray(int[] a, int x) {
boolean b = false;
for(int i=0; i<a.length; i++) {
if (x==a[i]) {
b = true;
break;
}
}
return b;
}

public int numBusesToDestination(int[][] routes, int S, int T) {
if (S==T) return 0;
int minDist = Integer.MAX_VALUE;

int h = routes.length;

List<Integer> list_S = new ArrayList<Integer>();
for (int i = 0; i < h; i++) {
for (int j = 0; j < routes[i].length; j++) {
if (routes[i][j]==S) {
list_S.add(i);
}
}
}

Map<Integer, List<Integer>> reachableRouteMap = new HashMap<Integer, List<Integer>>();
for(int i=0; i<h; i++) {
List<Integer> list = new ArrayList<Integer>();
for(int j=0; j<h; j++) {
if (j!=i && routesIntersect(routes[i],routes[j])) {
list.add(j);
}
}
reachableRouteMap.put(i,list);
}

boolean[] visited = new boolean[h];
for (int i = 0; i < h; i++) {
visited[i] = false;
}

Queue<Node> q = new LinkedList<>();
for(Integer i : list_S) {
Node s = new Node(i, 1);
q.add(s);
}

while (!q.isEmpty()) {
Node curr = q.poll();
visited[curr.route] = true;
if (inArray(routes[curr.route], T)) {
return curr.dist;
}
List<Integer> list = reachableRouteMap.get(curr.route);
for(Integer idx : list) {
if (visited[idx]==false) {
Node node = new Node(idx, curr.dist+1);
q.add(node);
}
}
}

if (minDist == Integer.MAX_VALUE)
minDist = -1;
return minDist;
}

class Node {
int route;
int dist;

public Node(int route, int dist) {
this.route = route;
this.dist = dist;
}
}
}

Submission Detail

  • 45 / 45 test cases passed.
  • Runtime: 1156 ms, faster than 5.02% of Java online submissions for Bus Routes.
  • Memory Usage: 48.2 MB, less than 100.00% of Java online submissions for Bus Routes.

5 tips to improve your critical thinking - Samantha Agoos - TED-Ed

Every day, a sea of decisions stretches before us. Some are small and unimportant, but others have a larger impact on our lives. For example, which politician should I vote for? Should I try the latest diet craze? Or will email make me a millionaire? We’re bombarded with so many decisions that it’s impossible to make a perfect choice every time. But there are many ways to improve our chances, and one particularly effective technique is critical thinking. This is a way of approaching a question that allows us to carefully deconstruct a situation, reveal its hidden issues, such as bias and manipulation, and make the best decision. If the critical part sounds negative that’s because in a way it is. Rather than choosing an answer because it feels right, a person who uses critical thinking subjects all available options to scrutiny and skepticism. Using the tools at their disposal, they’ll eliminate everything but the most useful and reliable information. There are many different ways of approaching critical thinking, but here’s one five-step process that may help you solve any number of problems.

One: formulate your question. In other words, know what you’re looking for. This isn’t always as straightforward as it sounds. For example, if you’re deciding whether to try out the newest diet craze, your reasons for doing so may be obscured by other factors, like claims that you’ll see results in just two weeks. But if you approach the situation with a clear view of what you’re actually trying to accomplish by dieting, whether that’s weight loss, better nutrition, or having more energy, that’ll equip you to sift through this information critically, find what you’re looking for, and decide whether the new fad really suits your needs.

Two: gather your information. There’s lots of it out there, so having a clear idea of your question will help you determine what’s relevant. If you’re trying to decide on a diet to improve your nutrition, you may ask an expert for their advice, or seek other people’s testimonies. Information gathering helps you weigh different options, moving you closer to a decision that meets your goal.

Three: apply the information, something you do by asking critical questions. Facing a decision, ask yourself, “What concepts are at work?” “What assumptions exist?” “Is my interpretation of the information logically sound?” For example, in an email that promises you millions, you should consider, “What is shaping my approach to this situation?” “Do I assume the sender is telling the truth?” “Based on the evidence, is it logical to assume I’ll win any money?”

Four: consider the implications. Imagine it’s election time, and you’ve selected a political candidate based on their promise to make it cheaper for drivers to fill up on gas. At first glance, that seems great. But what about the long-term environmental effects? If gasoline use is less restricted by cost, this could also cause a huge surge in air pollution, an unintended consequence that’s important to think about.

Five: explore other points of view. Ask yourself why so many people are drawn to the policies of the opposing political candidate. Even if you disagree with everything that candidate says, exploring the full spectrum of viewpoints might explain why some policies that don’t seem valid to you appeal to others. This will allow you to explore alternatives, evaluate your own choices, and ultimately help you make more informed decisions.

This five-step process is just one tool, and it certainly won’t eradicate difficult decisions from our lives. But it can help us increase the number of positive choices we make. Critical thinking can give us the tools to sift through a sea of information and find what we’re looking for. And if enough of us use it, it has the power to make the world a more reasonable place.

Go Cheat Sheet

cmd

go version

go env

gopath

The Go path is used to resolve import statements.

GOPATH is a list of directories (like PATH). Run go help gopath for details.

The GOPATH environment variable lists places to look for Go code.

  • On Unix, the value is a colon-separated string.
  • On Windows, the value is a semicolon-separated string.