LeetCode - 3Sum
Question Definition
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
More …Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
More …public class DepthFirstSearch {
private boolean[] marked;
private int count;
public DepthFirstSearch(Graph G, int s) {
marked = new boolean[G.V()];
dfs(G, s);
}
private void dfs(Graph G, int v) {
marked[v] = true;
count++;
for (int w : G.adj(v))
if (!marked[w]) dfs(G, w);
}
public boolean marked(int w) {
return marked[w];
}
public int count() {
return count;
}
}
import java.util.Stack;
public class DepthFirstPaths {
private final int s; // source
private boolean[] marked; // Has dfs() been called for this vertex?
private int[] edgeTo; // last vertex on known path to this vertex
public DepthFirstPaths(Graph G, int s) {
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
this.s = s;
dfs(G, s);
}
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v))
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
}
public boolean hasPathTo(int v) {
return marked[v];
}
public Iterable<Integer> pathTo(int v) {
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x])
path.push(x);
path.push(s);
return path;
}
}
import java.util.LinkedList;
import java.util.List;
public class Graph {
private final int V; // number of vertices
private int E; // number of edges
private List<Integer>[] adj; // adjacency lists
public Graph(int V) {
this.V = V;
this.E = 0;
adj = new LinkedList[V]; // Create array of lists.
for (int v = 0; v < V; v++) // Initialize all lists
adj[v] = new LinkedList<Integer>(); // to empty.
}
public int V() {
return V;
}
public int E() {
return E;
}
public void addEdge(int v, int w) {
adj[v].add(w); // Add w to v’s list.
adj[w].add(v); // Add v to w’s list.
E++;
}
public Iterable<Integer> adj(int v) {
return adj[v];
}
}
Given a sorted integer array without duplicates, return the summary of its ranges.
More …