并查集II

1. Longest Consecutive Sequence

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length:4.

Your algorithm should run in O(n) complexity.

先不考虑并查集,题目要求时间复杂度为O(n),考虑用哈希表保存数组元素。遍历数组元素,前后扩展查找相邻元素,并记录已查找过的元素,下次不再执行查找操作,记录最大连续序列长度即可。

public class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        HashSet<Integer> used = new HashSet<Integer>();
        int len = 0, max = 0;
        for(int e:nums) set.add(e);
        for(int i = 0;i < nums.length; i++){
            if(used.contains(nums[i])) continue;
            used.add(nums[i]);
            int j = nums[i] ,k = j;
            if(used.contains(++j)) continue;
            while(set.contains(j)) used.add(j++);
            if(used.contains(--k)) continue;
            while(set.contains(k)) used.add(k--);
            len = j-k-1;
            max = Math.max(len,max);
        }
        return max;
    }
}

这个题目给的tag是并查集,那么如何用并查集来做呢,我的想法是对元素的下标构建并查集,仍然需要hash,如果一个元素紧邻的前一个元素也存在就合并,统计每个集合的大小,从中取最大值即可。不过这种方法还没上面的简单。代码如下:

public class Solution {
    private static int[] father;
    public int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        HashSet<Integer> set = new HashSet<Integer>();
        father = new int[nums.length];
        for(int i = 0;i < nums.length;i++) father[i] = i;
        int[] count = new int[nums.length];
        
        int max = 1;
        for(int i = 0;i < nums.length; i++) {if(map.get(nums[i]) == null) map.put(nums[i],i);count[i]=1;}
        for(int i = 0;i < nums.length; i++){
            if(set.contains(nums[i])) continue;
            set.add(nums[i]);
            if(map.get(nums[i]-1) != null){
                int ra = find(i);
                int rb = find(map.get(nums[i]-1));
                if(ra != rb){
                    if(ra<rb) count[ra] += count[rb]; 
                    else count[rb] += count[ra];
                }
                union(i,map.get(nums[i]-1));
            }
        }
        for(int m:count) max = Math.max(m,max);
        return max;
    }
    public int find(int x){
        return x == father[x]?x:(father[x] = find(father[x]));
    }
    public void union(int a,int b){
        int ra = find(a);
        int rb = find(b);
        if(ra == rb) return;
        if(ra<rb) father[rb] = ra;
        else father[ra] = rb;
    }
}

2.Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

这题很适合用并查集来做,不过需要转换一下,对于二维数组的某个元素(i,j),我们把它转换为i*n+j。初始化时,把所有为'0'的点的father值设为father.length+1,这样最终统计结果时,便不会计算为0的区域,为'1'的点,正常初始化。遍历数组的过程中,假如当前为(i,j),且grid[i][j] = '1',如果grid(i,j+1) == '1',那么就对二者进行union操作,如果grid(i+1,j) == '1',同样对二者进行union操作。最终统计father[i] == i的个数就得到最终结果。代码如下:

public class Solution {
    private int[] father;
    private int m;
    private int n;
    public int numIslands(char[][] grid) {
        m = grid.length;
        if(m==0) return 0;
        n = grid[0].length;
        father = new int[m*n];
        init(grid);
        for(int i = 0;i <= m-1;i++){
            for(int j = 0;j <= n-1;j++){
                if(grid[i][j] == '1'){
                    if(j+1<n && grid[i][j+1] == '1') union(trans(i,j),trans(i,j+1));
                    if(i+1<m && grid[i+1][j] == '1') union(trans(i,j),trans(i+1,j));
                }
            }
        }
        int cnt = 0;
        for(int i = 0;i<father.length;i++){if(father[i] == i) cnt++;}
        return cnt;
    }
    private int trans(int i,int j){return i*n+j;}
    private int[] trans2(int num){int[] res = new int[2]; res[0] = num/n;res[1] = num%n; return res;}
    public void init(char[][] grid){
        int[] res = new int[2];
        for(int i = 0; i < father.length; i++) {
            res = trans2(i);
            if(grid[res[0]][res[1]] == '0')
                father[i] = father.length+1;
            else father[i] = i;
        }
    }
    public int find(int x){
        return x == father[x]?x:(father[x] = find(father[x]));
    }
    public void union(int a,int b){
        int ra = find(a);
        int rb = find(b);
        if(ra == rb) return;
        if(ra<rb)father[rb] = ra;
        else father[ra] = rb;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值