My solution is Time Limit Exceeded,how can do it beter.


  • 0
    Z

    class Solution {

    public:

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> index;
        int sizeOfArray = nums.size();
        char flag = 0;
        for(int i = 0;i < sizeOfArray - 1;i++)
        {
            if(flag == 1)
            {
                break;
            }
            for(int j = i + 1;j < sizeOfArray;j++)
            {
                if((nums[i] + nums[j]) == target)
                {
                    index.push_back(i + 1);
                    index.push_back(j + 1);
                    flag = 1;
                }
            }
        }
        return index;
    }
    

    };


  • 3
    Q

    Your solution is O(N^2) complexity. The best answer is to use HashMap to achieve O(N).

    For your solution, you can achieve O(N*Log(N)) using std::sort.


Log in to reply
 

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