My C++ Solution

  • 2
    class Solution {
        vector<int> twoSum(vector<int> &nums, int target) {
            vector<int> answer;
            int length = nums.size();
            bool successful = false;
            for (int i = 0; i < length; i++) {
                for (int j = i + 1; j < length; j++) {
                    if (target - == {
    //                    printf("%d %d\n",,;
                        answer.insert(answer.end(), i);
                        answer.insert(answer.end(), j);
                        successful = true;
            return answer;

  • 0

    It gets TLE on one case (I can not paste the test case cause it is too long). Obviously, the time complexity is O(n2), and one of the solution is also O(n2), so this code should be accepted.

    Thanks for any clue.

  • 0

    Why not just return answer instead of using successful to escape loops? Also, you could use answer.push_back(i);. This will add it to the end.

  • 0

    @betts Thanks!

Log in to reply

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