Problem Statement
Problem Statement
Given an unsorted array of integers nums, return the length of the longest
consecutive elements sequence.
Problem Understanding:
We have a bunch of numbers all mixed up. We want to see how long a chain of
numbers we can make where each number is just one more than the previous
one.
Here is Algorithm:
3. Remember Numbers:
Remember each number in the list you got earlier.
5. Find Groups:
Start counting from the remembered numbers.
Count the numbers next to each remembered number until you
can't find any more remembered numbers.
Record the length of each group of consecutive numbers.
6. Longest Group:
Check all the recorded group lengths.
Find the longest group.
Code:
class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Boolean> hm = new HashMap<>();
for(int i =0; i <nums.length; i++)
hm.put(nums[i], true);
int max = 0;
for(Integer key : hm.keySet()){
if(hm.get(key) == true){
max = Math.max(max, findLength(hm, key));
}
}
return max;
}
Output :
Problem Statement:
Problem Understanding:
For example:
Here is Algorithm:
import java.util.*;
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a,b)-> Integer.compare(a[0],b[0]));
Problem Statement:
Imagine you are looking at a city from far away.you see a line made by the tops
of all buildings. This line is called the city’s skyline,if you know where each
building is and how tall it is,can you draw this skyline? Given the locations and
heights of all the buildings, return the skyline formed by these buildings
collectively.
The geometric information of each building is given:
Problem understanding:
Every point in the skyline represents the beginning of a horizontal line that
finishes at the intersection of the last building and the ground level. Avoid
merging consecutive horizontal lines of the same height.
In other words we can say that the aim is to create a skyline based on the given
list of buildings. It uses a linked list structure to manage the buildings and their
heights efficiently.
Here is Algorithm:
Code:
import java.util.*;
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
List<List<Integer>> result = new ArrayList<>();
List<int[]> heights = new ArrayList<>();
for (int[] b : buildings) {
heights.add(new int[] {b[0], -b[2]});
heights.add(new int[] {b[1], b[2]});
}
PriorityQueue<Integer> pq = new
PriorityQueue<>(Collections.reverseOrder());
pq.offer(0);
int prev = 0;
for (int[] h : heights) {
if (h[1] < 0) {
pq.offer(-h[1]);
} else {
pq.remove(h[1]);
}
int curr = pq.peek();
if (prev != curr) {
List<Integer> point = new ArrayList<>();
point.add(h[0]);
point.add(curr);
result.add(point);
prev = curr;
}
}
return result;
}
}
Output:
Skyline 1: [[2, 10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0]]
Skyline 2: [[0, 3], [5, 0]]