LeetCode·Daily Problem·822. Flip Card Game·Hash

Author: Xiao Xun
Link: https://leetcode.cn/problems/card-flipping-game/solutions/2368969/ha-xi-zhu-shi-chao-ji-xiang-xi-by-xun-ge-7ivj/
Source: LeetCode
copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

topic

train of thought

According to the meaning of the question, as long as there are numbers satisfying fronts[i]=backs[i], then fronts[i] is absolutely impossible to be the answer, otherwise fronts[i] or backs[i] can meet the requirements as the number on the back, take the minimum value as an answer.

We can traverse the array first, find the number that satisfies fronts[i]=backs[i], and store it in the hash table hash. Then traverse the array again, find the number that is not in the hash, and take the minimum value as the answer. Returns 0 if all numbers are in forbidden

For the implementation of hash, you can use a hash library. Of course, the data size of this question is relatively small, so you can use array hash, which is more convenient.

Code comments are super detailed

the code


int flipgame(int* fronts, int frontsSize, int* backs, int backsSize){
    int hash[2001] = {0};//数组哈希
    for (int i = 0; i < frontsSize; ++i) {
        if (fronts[i] == backs[i]) {//加入哈希表
            ++hash[fronts[i]];
        }
    }
    int min = INT_MAX;
    for (int i = 0; i < frontsSize; ++i) {
        if (hash[fronts[i]] == 0) {//不在哈希表中的元素
            min = fmin(min, fronts[i]);//取最小值
        }
        if (hash[backs[i]] == 0) {
            min = fmin(min, backs[i]);
        }
    }
    return min == INT_MAX ? 0 : min;
}

作者:小迅
链接:https://leetcode.cn/problems/card-flipping-game/solutions/2368969/ha-xi-zhu-shi-chao-ji-xiang-xi-by-xun-ge-7ivj/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/m0_64560763/article/details/132055426