Why is my code time-exceed using iterator?


  • 0
    C
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
           vector<int>::iterator it1,it2;
             for(it1=nums.begin();it1!=nums.end();it1++)
             for(it2=it1;it2!=nums.end();it2++)
                if(*it1+*it2==target)
                {
                    vector<int> result;
                    result.push_back(it1-nums.begin());
                    result.push_back(it2-nums.begin());
                    return result;
                }
        }
    };

  • 0
    K

    You code's time complexity is O(n^2), which is easily prone to TLE when the size of nums is large.


Log in to reply
 

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