Problem
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/description/
Solution
// 1. map 에 key 는 숫자, value 는 저장된 index 를 저장
// 2. sliding window 움직이되, left 는 map 에 right 가 존재하면 해당 index 로 옮긴다
class Solution {
public int minimumCardPickup(int[] cards) {
int result = Integer.MAX_VALUE;
int left = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int right=0;right<cards.length;right++) {
int card = cards[right];
if(map.containsKey(card)) {
left = map.get(card);
result = Math.min(result, right - left + 1);
}
map.put(card, right);
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}
- Sliding window + HashMap 로 푸는 문제!
- left 를 이동시킬 때 조건이 메인 포인트

Leave a comment