最長連續序列計算
阿新 • • 發佈:2022-04-06
題目
輸入一個無序的整數陣列, 請計算最長的連續數值序列的長度。例如,輸入陣列
[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); } }