https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/
Minimum Consecutive Cards to Pick Up - LeetCode
Can you solve this real interview question? Minimum Consecutive Cards to Pick Up - You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value. Return the minimum n
leetcode.com
- 난이도: medium
- Time complexity : O(n)
- 숙지할것:
- unordered_map<int,vector<int>> hash; // key,value에자리에서 value 의 형태로 vector를 선언하여 link된 list로 만들수있음
- 이 문제는 sliding window 방식으로도 풀 수 있지만 hash를 이용할 수 있음. hash 로 접근했을때는 value들 값안에 index값이 들어가 이 인덱스간 길이가 가장 짧은것을 반환하면 subarray를 쉽게 구할 수있다 .
- hash 가 들어간 문제를 풀때는 table을 그려보고 그안에 key , value에 어떤값이 와야할지 선택하면서 접근하기.
class Solution {
public:
int minimumCardPickup(vector<int>& cards) {
unordered_map<int,vector<int>> hash;
for(int i =0 ; i < cards.size(); i++){
hash[cards[i]].push_back(i);
}
int ans = INT_MAX;
for(auto[key,arr]:hash){
for(int i =0; i < arr.size()-1 ; i++ ){
ans = min(ans, arr[i+1]-arr[i]+1 );
}
}
return ans ==INT_MAX ? -1:ans ;
}
};
'Data Structure & Algorithms > Hasing' 카테고리의 다른 글
| [Hashing] 해쉬를 핵심만 정리해보자 (0) | 2023.03.12 |
|---|---|
| [Hashing] 383. Ransom Note (0) | 2023.01.06 |
| [Hashing] Find Players With Zero or One Losses (0) | 2023.01.06 |
| [Hashing] Largest Unique Number (0) | 2023.01.04 |
| [Hashing] Maximum Number of Balloons (0) | 2023.01.03 |
댓글