[算法与数据结构][array operations][leetcode1512:medium]Number of Good Pairs

https://leetcode.com/problems/number-of-good-pairs/submissions/

先记录三段代码

class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        map<int, vector<int>> val_to_idx;
        int res = 0;
        for(int i=0;i<nums.size();i++){
            auto it = val_to_idx.find(nums[i]);
            if(it != val_to_idx.end()){
                res += it->second.size();
                it->second.push_back(i);
            }else{
                val_to_idx[nums[i]]={i};
            }
        }
        return res;
    }
};
class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        int c[101] = {0};
        int res = 0;
        for(int i=0;i<nums.size();i++){
            if(c[nums[i]]>0){
                res += c[nums[i]];
                c[nums[i]]++;
            }else{
                c[nums[i]]=1;
            }
        }
        return res;
    }
};
class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        int c[101] = {0};
        int res = 0;
        for(int i=0;i<nums.size();i++){
            res += c[nums[i]]++ ;
        }
        return res;
    }
};
class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        int c[101] = {0};
        for(int n: nums ) c[0] += c[n]++;
        return c[0];
    }
};

你可能感兴趣的:(算法和数据结构)