美文网首页
Leetcode923:三数之和的多种可能性

Leetcode923:三数之和的多种可能性

作者: VIELAMI | 来源:发表于2020-07-18 12:32 被阅读0次

    【思路】
    先用数组统计各个数字出现的次数
    再遍历所有可能的 i j 此时 k会自动出现
    i <= j <= k 且 k >= 0 k <= size 不然会有问题 才能符合题目要求

    【代码】

    int threeSumMulti(vector<int>& A, int target) {
        //Leetcode923:三数之和的多钟可能
        //initialize some const
        int kMod = 1e9 + 7;
        int kMax = 100;
        
        //calculate frequency
        vector<long> freq(kMax + 1, 0);
        for (int a : A){
            freq[a]++;
        }
        
        long ans = 0;
        
        //for different condition calculate the result and add together
        for (int i = 0; i <= target; i++){
            for (int j = i; j <= target; j++){
                int k = target - i -j;
                //checkt whether the value k is legal
                if (k < 0 || k >= freq.size()|| k < j) continue;
                //check whether the number exits in A
                if (!freq[i]||!freq[j]||!freq[k]) continue;
                
                //condition 1
                if((i == j)&&(j == k)){
                    ans += freq[i] * (freq[i] - 1) * (freq[i] - 2)/6;
                }
                //condition2
                else if((i == j)&& (j != k)){
                    ans += freq[k] * freq[i] * (freq[i] - 1) /2;
                }
                //condition 3
                else if ((i != j) && (j == k)){
                    ans += freq[i] * freq[j] * (freq[j] - 1) /2;
                }
                //condition 4
                else {
                    ans += freq[i] * freq[j] * freq[k];
                }
            }
        }
        return ans%kMod;
    
    }
    
    

    相关文章

      网友评论

          本文标题:Leetcode923:三数之和的多种可能性

          本文链接:https://www.haomeiwen.com/subject/gnixkktx.html