首页 > 其他 > 详细

leetcode 982

时间:2019-05-14 21:14:14      阅读:122      评论:0      收藏:0      [点我收藏+]

技术分享图片

技术分享图片

题意:寻找一个整数数组A中的三个数,使得它们与为0

思路:使用 unordered_map , key键存储两层for循环后得到的与值,再将unordered_map的所有key值与A里的所有值相与,若为0则将 A.second 加到cnt中。

class Solution {
public:
    int countTriplets(vector<int>& A) {
        int cnt = 0;
        unordered_map<int , int> tri;
        for(auto i:A)
            for(auto j : A)
                ++tri[i&j];
        for(auto k:A)
            for(auto t:tri)
                if((k & t.first) == 0)
                    cnt += t.second;
        return cnt;
    }
};

技术分享图片

时间复杂度分析:因为A[i]的最大值为2^16,所以map的最多存储2^16个数,时间复杂度为  O(n*n)

leetcode 982

原文:https://www.cnblogs.com/Bella2017/p/10864410.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!