From d9eb0142af20a2979364f2b88a85a9ef294fbaf6 Mon Sep 17 00:00:00 2001 From: wyl <959814898@qq.com> Date: Tue, 25 Jun 2024 17:33:54 +0800 Subject: [PATCH] =?UTF-8?q?leetcode=20128.=E6=9C=80=E9=95=BF=E8=BF=9E?= =?UTF-8?q?=E7=BB=AD=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/wyl/leetcode/LongestConsecutive.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 leetcode/src/main/java/com/wyl/leetcode/LongestConsecutive.java diff --git a/leetcode/src/main/java/com/wyl/leetcode/LongestConsecutive.java b/leetcode/src/main/java/com/wyl/leetcode/LongestConsecutive.java new file mode 100644 index 0000000..a8197a9 --- /dev/null +++ b/leetcode/src/main/java/com/wyl/leetcode/LongestConsecutive.java @@ -0,0 +1,43 @@ +package com.wyl.leetcode; + +import java.util.Arrays; + +/** + * 128.给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 + *

+ * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 + *

+ * 示例 1: + *

+ * 输入:nums = [100,4,200,1,3,2] + * 输出:4 + * 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。 + * 示例 2: + *

+ * 输入:nums = [0,3,7,2,5,8,4,6,0,1] + * 输出:9 + */ +public class LongestConsecutive { + static public int longestConsecutive(int[] nums) { + Arrays.sort(nums); + if (nums.length == 0) { + return 0; + } + int num = 1; + int max = 1; + for (int i = 0, j = 1; j < nums.length; i++, j++) { + if ((nums[j] - nums[i]) == 1) { + num++; + } else if ((nums[j] - nums[i]) == 0) { + } else { + max = Math.max(max, num); + num = 1; + } + } + return Math.max(max, num); + } + + public static void main(String[] args) { + System.out.println(longestConsecutive(new int[]{1, 2, 0, 1})); + } +}