Find the longest subarray with distinct entries
longest-subarray-with-distinct-entries.cc LongestSubarrayWithDistinctEntries.javapublic static int longestSubarrayWithDistinctEntries(List<Integer> A) {
// Records the last occurrences of each entry.
Map<Integer, Integer> lastOccurrence = new HashMap<>();
int startingIdx = 0, ans = 0;
for (int i = 0; i < A.size(); ++i) {
Integer result = lastOccurrence.put(A.get(i), i);
if (result != null) { // A[i] appeared before. Check its validity.
if (result >= startingIdx) {
ans = Math.max(ans, i - startingIdx);
startingIdx = result + 1;
}
}
}
ans = Math.max(ans, A.size() - startingIdx);
return ans;
}