Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

tag : union find

create the array first and then union the consecutive number (3,4)  (4,5) -- > have the same root

e.g: 100   4   200  1   3  2

100  4   200   1   3  2

My method: weighted union find with hashmap;

Solution 1

class Solution {
//union find
class QuickUnion {//with array
HashMap<Integer, Integer> map = new HashMap<>(); // id, parent
HashMap<Integer, Integer> sz = new HashMap<>(); // id size
int count;//how many components
QuickUnion(int[] nums){
count = 1;
for(int i = 0; i<nums.length;i++) {
map.put(nums[i],nums[i]);
sz.put(nums[i],1);
}
}
Integer root(int p){
if(!map.containsKey(p)) return null; // there is no such id while(p != map.get(p)){
int temp = map.get(map.get(p));//with path compression , set parent -> grandparent, map.get(i): i 's parent
map.put(p, temp);
p = map.get(p);
} /*while(id[p] != p){//find the root when to stop
id[p] = id[id[p]];
p = id[p];
}*/
return p;
}
boolean find(int p, int q){
return root(p)==root(q);
}
void union(int p, int q){
//get root
Integer pid = root(p);
Integer qid = root(q);
System.out.println(qid);
if(pid == null || qid == null) return; // check the null
//if(pid == qid) return; // check the integer,. heck if in the same set
if(pid.equals(qid)) return;
if(sz.get(pid) > sz.get(qid)){
map.put(qid, pid);
sz.put(pid, sz.get(pid)+sz.get(qid));
if(sz.get(pid)>count) count = sz.get(pid);
}else{
map.put(pid, qid);
sz.put(qid, sz.get(pid)+sz.get(qid));
if(sz.get(qid)>count) count = sz.get(qid);
} }
}
public int longestConsecutive(int[] nums) {
//create a union find
//union the elemnt 4 (3,5) -> 3,4,5
if(nums.length == 0) return 0;
QuickUnion qu = new QuickUnion(nums);
for(int i = 0; i<nums.length; i++){
System.out.println("num of i"+i+" ");
if(nums[i] != Integer.MIN_VALUE) qu.union(nums[i],nums[i]-1);//check the boundary
if(nums[i] != Integer.MAX_VALUE) qu.union(nums[i],nums[i]+1);//[2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645]
System.out.println(qu.count+" ");
}
return qu.count;
}
}

Solution: hashset

remove and contains in ahshset

flow: remove the element : visited that element

class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length==0) return 0;
//use hashset
HashSet<Integer> set = new HashSet<>();//non duplicate element
for(int num : nums){
set.add(num);
} int max = 1;
for(int num : nums){
int len = 0;
int left = 1, right = 1;
if(!set.contains(num)) continue; while(set.contains(num-left)){
set.remove(num-left); left++; len++;
}
while(set.contains(num+right)){
set.remove(num+right); right++; len++;
}
len++;
set.remove(num);
max = Math.max(len, max); }
return max;
}
}

quick find and quick union and weightedunion find

public class QuickFind{
private int[] id; // set all root of current id public QuickFind(int N){
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
//Check if p and q have the same id.
boolean find(int p, int q){
return id[p]==id[q];
}
//union pq
void unite(int p, int q){
int pid = id[p];//change pid to q
for(int i = 0; i <id.length; i++){
if(id[i] == pid) id[i] = id[q];
}
} } public class QuickUnion{
private int[] id; //represent the parent instead of root public QuickUnion(int N){
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
//Check if p and q have the same id.
boolean find(int p, int q){
return root(p)==root(q);
}
//get the root
int root(int i){
while(i != id[i]) i = id[i];//id[i] parent i: children
return i;
}
//union p q
void unite(int p, int q){
//find root first
int i = root(p);
int j = root(q);
id[i] = j;
}
} //avoid the tall trees , keep track ther size of each component
public class WeightedQuickUnion{
private int[] id; //represent the parent instead of root
private int[] sz;
int count;
public WeightedQuickUnion(int N){
count = N;
id = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++){
id[i] = i;
sz[i] = 1;
} }
//Check if p and q have the same id.
boolean find(int p, int q){
return root(p)==root(q);
}
//get the root
int root(int i){
while(i != id[i]) {
// path compression
id[i] = id[id[i]];
i = id[i];//id[i] parent i: children
}
return i;
}
//union p q
void unite(int p, int q){
//find root first
int i = root(p);
int j = root(q);
if(sz[i]<sz[j]){ //samller tree to larger tree
id[i] = j; sz[j]+=sz[i];
}else {
id[j] = i; sz[i]+=sz[j];
}
count--;
}
}

Leetcode 128. Longest Consecutive Sequence (union find)的更多相关文章

  1. [LeetCode] 128. Longest Consecutive Sequence 求最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  2. [LeetCode] 128. Longest Consecutive Sequence 解题思路

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  3. Java for LeetCode 128 Longest Consecutive Sequence

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  4. leetcode 128. Longest Consecutive Sequence ----- java

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  5. [leetcode]128. Longest Consecutive Sequence最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Y ...

  6. LeetCode 128 Longest Consecutive Sequence 一个无序整数数组中找到最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.Fo ...

  7. Leetcode#128 Longest Consecutive Sequence

    原题地址 1. 把所有元素都塞到集合里2. 遍历所有元素,对于每个元素,如果集合里没有,就算了,如果有的话,就向左向右拓展,找到最长的连续范围,同时在每次找的时候都把找到的删掉.这样做保证了同样的连续 ...

  8. 128. Longest Consecutive Sequence(leetcode)

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  9. 【LeetCode】128. Longest Consecutive Sequence

    Longest Consecutive Sequence Given an unsorted array of integers, find the length of the longest con ...

随机推荐

  1. Hdu 5862 Counting Intersections(有n条线段,每一条线段都是平行于x轴或者y轴,问有多少个交点+树状数组区间求和单点跟新)

    传送门:Hdu 5862 Counting Intersections 题意:有n条线段,每一条线段都是平行于x轴或者y轴,问有多少个交点 分析: 基本的操作流程是:先将所有的线段按照横树坐标x按小的 ...

  2. Linux内核硬件访问技术

    ① 驱动程序控制设备,主要是通过访问设备内的寄存器来达到控制目的.因此我们讨论如何访问硬件,就成了如何访问这些寄存器. ② 在Linux系统中,无论是内核程序还是应用程序,都只能使用虚拟地址,而芯片手 ...

  3. mysql 示例数据库安装

    示例数据库不和bin安装文件在一块, 安装数据库没有这个选项 https://dev.mysql.com/doc/index-other.html

  4. ETL的两种架构(ETL架构和ELT架构)

     ETL ETL,是英文 Extract-Transform-Load 的缩写,用来描述将数据从来源端经过抽取(extract).转换(transform).加载(load)至目的端的过程.ETL一词 ...

  5. python 下载图片

    import requests from PIL import Image from io import BytesIO url = 'http://image2.buslive.cn/shp/upl ...

  6. POI 按word模版生成合同并生成PDF

    功能需求:根据用户给的word版本合同文件.docx,实现模版替换功能. 如: 功能:支持段落和表格里的文字替换,还可以支持表格替换.如果需要段落需要换行用<br>隔开如:身份证<b ...

  7. PHP文件上传error的错误类型 - $_FILES['file']['error']

    假设文件上传字段的名称img,则: $_FILES['img']['error']有以下几种类型 1.UPLOAD_ERR_OK 其值为 0,没有错误发生,文件上传成功. 2.UPLOAD_ERR_I ...

  8. ubuntu下搭建android开发环境核心篇安装AndroidStudio、sdk、jdk

    本文系转载http://blog.csdn.net/lsyz0021/article/details/52215996 一.安装前的准备 1.1.如果你还没有安装ubuntu 14.04 LTS系统, ...

  9. iscroll.js文档

    iScroll是高性能的.小尺寸的.无依赖关系的.支持多平台的滑动JavaScript库. 当然,不只是scroll,还有滚动.缩放.平移.无限滚动.视差滚动等. 为了达到更好的新能,所以iScrol ...

  10. for循环笔记

    JS获取元素方法——ById和ByTagName方法的区别 1.通过id获取,前面就只能是document,不能是其他的,但是ByTagName前面可以是document,也可以跟一个别的元素 #li ...