Java for Leetcode longest consecutive Sequence

Source: Internet
Author: User

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2] ,
The longest consecutive elements sequence is [1, 2, 3, 4] . Return its length: 4 .

Your algorithm should run in O (n) complexity.

Problem Solving Ideas:

Because of the time complexity of O (n), and therefore cannot be implemented by the sort, the topic is somewhat similar to the first question of Java for Leetcode 001 The second Sum also needs to be implemented with HashMap, the specific idea is to first put Nums into the map, Then for each element of the nums, check its "sphere of influence" (the subject does not involve repeating elements), the Java implementation is as follows:

public int longestconsecutive (int[] nums) {hashmap<integer, boolean> HM = new Hashmap<integer, boolean> ();  int res = 0;for (int num:nums) hm.put (num, False), for (int num:nums) {if (Hm.get (num)) continue;int width = 1;for (int j = 1; Hm.containskey (NUM-J); J + +, width++) Hm.put (Num-j, True), for (int j = 1; Hm.containskey (num + j); J + +, width++) hm.put (num + j, true); res = Math. Max (res, width);} return res;}

Java for Leetcode longest consecutive Sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.