其他分享
首页 > 其他分享> > 最长连续序列计算

最长连续序列计算

作者:互联网

题目

输入一个无序的整数数组, 请计算最长的连续数值序列的长度。例如,输入数组[10,5,9,2,4,3],则最长的连续序列是[2,3,4,5],输出长度为4

解法

使用广度优先遍历

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int longestConsecutive(int[] nums) {
        int longest = 0;
        Set<Integer> set = new HashSet<>();
        for (int num: nums
             ) {
            set.add(num);
        }

        for (int i = 0; i < nums.length; i++) {
            longest = Math.max(bfs(set, nums[i]), longest);
        }
        return longest;

    }

    private int bfs(Set<Integer> set, int num) {
        int length = 1;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(num);
        set.remove(num);
        while (!queue.isEmpty()){
            int i = queue.remove();
            int[] neighbors = {i + 1, i - 1};
            for (int neighbor: neighbors
                 ) {
                if (set.contains(neighbor)){
                    length++;
                    queue.add(neighbor);
                    set.remove(neighbor);
                }
            }
        }
        return length;
    }
}

使用并查集

class Solution {
    public int longestConsecutive(int[] nums) {
        Map<Integer, Integer> fathers = new HashMap<>();
        Map<Integer, Integer> counts = new HashMap<>();
        Set<Integer> all = new HashSet<>();

        for (int num: nums
             ) {
            fathers.put(num, num);
            counts.put(num, 1);
            all.add(num);
        }

        for (int num: nums
             ) {
            if (all.contains(num + 1)){
                union(fathers, counts, num, num + 1);
            }
            if (all.contains(num - 1)){
                union(fathers, counts, num, num - 1);
            }
        }
        int longest = 0;
        for (int count: counts.values()
             ) {
            longest = Math.max(count, longest);
        }
        return longest;
    }

    private void union(Map<Integer, Integer> fathers, Map<Integer, Integer> counts, int i, int j) {
        int fatherOfI = findFather(fathers, i);
        int fatherOfJ = findFather(fathers, j);

        if ( fatherOfI != fatherOfJ){
            fathers.put(fatherOfI, fatherOfJ);
            int countOfI = counts.get(fatherOfI);
            int countOfJ = counts.get(fatherOfJ);
            counts.put(fatherOfJ, countOfI + countOfJ);
        }
    }

    private int findFather(Map<Integer, Integer> fathers, int num) {
        if (fathers.get(num) != num)
            fathers.put(num, findFather(fathers, fathers.get(num)));
        return fathers.get(num);
    }
}

标签:set,int,fathers,num,longest,计算,序列,counts,最长
来源: https://www.cnblogs.com/yefuyi/p/16106876.html