Given an unsorted array of integers
nums
, return the length of the longest consecutive elements sequence.Example 1:
Input: nums = [100,4,200,1,3,2] Output: 4
Approach
Java
import java.util.Arrays;public class LongestConsecutiveSequence {public static void main(String[] args) {int[] nums = { 100, 4, 200, 1, 3, 2 };System.out.println(longestConsecutive(nums));}// method to find the length of longest// consecutive sequencestatic int longestConsecutive(int[] nums) {if (nums.length == 0)return 0;Arrays.sort(nums);int cnt = 1, res = 1;for (int i = 1; i < nums.length; i++) {if (nums[i] == 1 + nums[i - 1]) {cnt++;} else if (nums[i] == nums[i - 1])continue;else {res = Math.max(res, cnt);cnt = 1;}}res = Math.max(res, cnt);return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the length of longest//consecutive sequenceint longestConsecutive(vector<int>& nums){sort(nums.begin(),nums.end());if(nums.size()==0)return 0;int cnt=1,res=1;for(int i=1;i<nums.size();i++){if(nums[i]==1+nums[i-1]){cnt++;}else if(nums[i]==nums[i-1])continue;else{res=max(res,cnt);cnt=1;}}res=max(res,cnt);return res;}int main(){vector<int> nums = {100,4,200,1,3,2};cout<<longestConsecutive(nums);return 0;}
No comments:
Post a Comment