My C++ Solution


  • 2
    class Solution {
    public:
        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 - nums.at(i) == nums.at(j)) {
    //                    printf("%d %d\n", nums.at(i), nums.at(j));
    
                        answer.insert(answer.end(), i);
                        answer.insert(answer.end(), j);
                        successful = true;
                        break;
                    }
                }
                if(successful)
                    break;
            }
            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
    B

    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
    G

    @betts Thanks!


Log in to reply
 

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