Leetcode Longest Consecutive Sequence

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.


[code]

public class Solution {
    public int longestConsecutive(int[] num) {
                if(num==null || num.length==0)return 0;
                HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
                for(int i=0;i<num.length;i++)
                {
                    map.put(num[i], 1);
                }
                int max=1;
                //[100, 4, 200, 1, 3, 2] (100 4 200 1 3 2)
                for(Integer e:map.keySet())
                {
                    int temp=e, length=0;
                    while(map.containsKey(temp) && map.get(temp)>0 )
                    {
                        length++;
                        map.put(temp, 0);
                        temp++;
                    }
                    temp=e-1;
                    while(map.containsKey(temp) && map.get(temp)>0 )
                    {
                        length++;
                        map.put(temp, 0);
                        temp--;
                    }
                    max=Math.max(max, length);
                }
                return max;
            }
}

[Thoughts]

  • 题意是duplicate元素只算一个
  • 虽然上面是AC代码,但是应该使用ConcurrentHashMap.
关于ConcurrentModificationException
  • 官方API:For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it.Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.
    Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
  • 对于HashSet,iterator可以remove(),但是只能remove()当前entry.
  • 对于HashMap, 没有iterator() method, 但是keySet(), ValueSet(),EntrySet() 都是fail-fast的iterator方法
  • ConcurrentHashMap and CopyOnWriteArrayList
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值