Archives
Trending
Support
Login
clear text
XML
Django
JavaScript
MATLAB
C
C++
C#
Python
SQL
Shell
Bash
Markdown
YAML
JSON
HTML
CSS
PHP
Java
Ruby
Go
Rust
Swift
Kotlin
Arduino
TypeScript
Perl
Autohotkey
Lua
SQF
R
Scala
Haskell
Groovy
Dart
Clojure
VB.NET
Objective-C
PowerShell
Bash
CoffeeScript
Verilog
// Longest Consecutive Sequence - https://leetcode.com/problems/longest-consecutive-sequence/description/ class Solution { // Sorting // Time Complexity: O(nlogn) // Space Complexity: O(1) // public int longestConsecutive(int[] nums) { // if(nums.length == 0) { // return 0; // } // int maxCount = 1; // Arrays.sort(nums); // for(int i = 0; i < nums.length - 1; i++) { // int count = 1; // while(i < nums.length - 1 // && (nums[i] + 1 == nums[i + 1] // || nums[i] == nums[i + 1])) { // if ( i < nums.length - 1 && nums[i] == nums[i + 1]) { // i++; // continue; // } // count++; // i++; // } // if (count > maxCount) { // maxCount = count; // } // } // return maxCount; // } // HashSet // Time Complexity: O(n) // Space Complexity: O(n) public int longestConsecutive(int[] nums) { if(nums.length == 0) { return 0; } Set
set = new HashSet<>(); for(int num: nums) { set.add(num); } int maxCount = 1; for(int num: set) { if(!set.contains(num - 1)) { int count = 1; while(set.contains(num + count)) { count++; } maxCount = Math.max(count, maxCount); } } return maxCount; } }
Mark as private (unlisted)
for 30 minutes
for 6 hours
for 1 day
for 1 week
for 1 month
for 1 year
everlasting (like CCCP)