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