Got accepted by using vectors of map but not by arrays of map in c++.Can anyone explain why ?


  • 0
    A

    Hello guys while I was trying this solution and the solution got accepted when used vectors of map in c++ but when I used arrays of map I got TLE . I always thought that arrays are faster than vectors and even some sites say the same(https://hackernoon.com/c-investigation-arrays-vs-vectors-e9ba864468b6) . Can anyone explain why this happened?
    My Source code with Arrays:

    class Solution {
    public:
        int numberOfArithmeticSlices(vector<int>& A) {
             if(A.size()<=2)
                return 0;
            int cnt=0;
            map<long int,int> m[A.size()];
            for(int i=0;i<A.size();i++){
                for(int j=0;j<i;j++){
                    long int diff=(long)A[i]-(long)A[j];
                    if(diff>=INT_MAX || diff<=INT_MIN)
                        continue;
                    int val=m[j][diff];
                    m[i][diff]+=val+1;
                    cnt+=val;
                }
            }
            return cnt;
        }
    };
    

    My Source code with Vectors:

    class Solution {
    public:
        int numberOfArithmeticSlices(vector<int>& A) {
            if(A.size()<=2)
                return 0;
            int cnt=0;
            vector<map<int,int>> m(A.size());
            for(int i=0;i<A.size();i++){
                for(int j=0;j<i;j++){
                    long int diff=(long)A[i]-(long)A[j];
                    if(diff>=INT_MAX || diff<=INT_MIN)
                        continue;
                    int val=m[j][diff];
                    m[i][diff]+=val+1;
                    cnt+=val;
                }
            }
            return cnt;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.