DEV Community

hwangs12
hwangs12

Posted on

Two Sum - O(n^2) solution

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        int i = 0;
        int j;
        vector<int> sol;

        while (i < nums.size())
        {

            j = i+1;

            while (j < nums.size())
            {
                if (nums[i] + nums[j] == target)
                {
                    sol.push_back(i);
                    sol.push_back(j);
                    break;
                }
                else
                {
                    ++j;
                    continue;
                }

            }
            if (sol.size() > 0) {
                break;
            }

            ++i;
        }

        return sol;
    }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)