Day 15 of 100 - Java: Graph data structure

j143

Janardhan Pulivarthi

Posted on January 23, 2022

Day 15 of 100 - Java: Graph data structure

Graph data structure with Java


class Graph {

  class Edge {
    int src, dest;
  }

  // Number of vertices and edges
  int vertices, edges;

  Edge[] edge;

  Graph(int vertices, int edges) {
    this.vertices = vertices;
    this.edges = edges;

    edge = new Edge[edges];
    for (int i = 0; i < edges; i++) {
      edge[i] = new Edge();
    }
  }

  public static void main(String[] args) {
    int numVertices = 5;
    int numEdges = 7;
    Graph g = new Graph(numVertices, numEdges);

    g.edge[0].src = 1;
    g.edge[0].dest = 2;

    g.edge[1].src = 1;
    g.edge[1].dest = 3;

    g.edge[2].src = 1;
    g.edge[2].dest = 4;

    g.edge[3].src = 2;
    g.edge[3].dest = 3;

    g.edge[4].src = 2;
    g.edge[4].dest = 4;

    g.edge[5].src = 3;
    g.edge[5].dest = 5;

    g.edge[6].src = 4;
    g.edge[6].dest = 5;

    for (int i = 0; i < numEdges; i++) {
      System.out.println(g.edge[i].src + " - " + g.edge[i].dest);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

https://github.com/j143/java-graph-datastructure-example

Java Collections conversions

Java List or ArrayList to Array

ArrayList homekeys = new ArrayList<> ();

homekeys.add("A");
homekeys.add("S");
homekeys.add("D");
homekeys.add("F");

// Create new Array

String[] homekeysArray = new String[homekeys.size()];

homekeys.toArray(homekeysArray);

Enter fullscreen mode Exit fullscreen mode

But, the other way around is simple

// import java.util.Arrays;

String[] array = {"A", "S", "D", "F"};

List languages = new ArrayList<> (Arrays.asList(array))
Enter fullscreen mode Exit fullscreen mode

Based on the above learning I have solved https://leetcode.com/problems/rearrange-array-elements-by-sign/ but got Time Limit Exceeded.

💖 💪 🙅 🚩
j143
Janardhan Pulivarthi

Posted on January 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024