思想:
序列无序且要求O(n),哈希最有可能。
线性的找一个可以向两边扩张最大的元素,返回扩张的长度。
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, bool> used;
for(auto i: num)
used[i] = false;
int longest = 0;
for(auto i: num) {
if(used[i])
continue;
int length = 1;
used[i] = true;
for(int j = i + 1; used.find(j) != used.end(); j++) {
used[j] = true;
length++;
}
for(int j = i - 1; used.find(j) != used.end(); j--) {
used[j] = true;
length++;
}
longest = max(longest, length);
}
return longest;
}
};
std::unordered_map
template < class Key, // unordered_map::key_type class T, // unordered_map::mapped_type class Hash = hash<Key>, // unordered_map::hasher class Pred = equal_to<Key>, // unordered_map::key_equal class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type > class unordered_map;
Unordered Map
Unordered maps are associative containers that store elements formed by the combination of a
key value and a
mapped value, and which allows for fast retrieval of individual elements based on their keys.
In an unordered_map, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. Types of key and mapped value may differ.
Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).
unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.
Unordered maps implement the direct access operator ( operator[]) which allows for direct access of the mapped valueusing its key value as argument.
Iterators in the container are at least forward iterators.