Insist on doing small things, then witness the magic
12345678910111213
class Solution { public int minimumCardPickup(int[] cards) { Map<Integer, Integer> lastOccur = new HashMap<>(); int ans = Integer.MAX_VALUE; for (int i = 0; i < cards.length; i++) { if (lastOccur.containsKey(cards[i])) { ans = Math.min(ans, i - lastOccur.get(cards[i]) + 1); } lastOccur.put(cards[i], i); } return ans == Integer.MAX_VALUE ? -1 : ans; }}
用hashmap记录每个值最后一次出现的index是多少.
时间复杂度: O(n)空间复杂度: O(n)
Calm Patient Persistent