Runtime Error in my C++ code


  • 0
    G

    I'm not understanding what's wrong with my code. Maybe I am misunderstanding the requested format for the output, but here is my code:

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

     // The 2  variables below are used to mark the desired values that add up to the target 
     int x,y;
     x=0;
     y=0;
     
     int max = nums.size();
     
     // The 2 variables below are what will be used for the output
     int answerA, answerB;
     answerA=0;
     answerB=0;
     
     bool found = false;
     
     while (found == false){
        for(int a = 1; a <= max ; a++){
         
         for(int b = 1; b <= max ; b++){
              
               if(nums[a] + nums [b] == target){
                  found = true;
                  x = a;
                  y = b;
               }
                 
            if(found) 
            break;
         }
            
           if(found)    
           break;
        }
     }
     
     if(nums[x] < nums[y]){
         answerA = x;
         answerB = y;
     }
     
     else if(nums[y] < nums[x]){
         answerA = y;
         answerB = x;
     }
     
     cout << "index1=" << answerA << ", index2=" << answerB << endl;
    
    }
    

    };


  • 1
    A

    I havent looked at your code but you are expected to return a vector. Rather than cout, push those two elements in a vector and return:

    vector<int> indices;
    
    //your code here
    
    indices.push_back(answerA);
    indices.push_back(answerB);
    
    return indices;
    

    Update:

    'indices' here is of type vector that holds 'int' values , hence the declaration:

    vector<int> indices
    

    For more information about vectors read here -http://www.cplusplus.com/reference/vector/vector/

    When you start writing the code, look at the function prototype provided to you by leetcode. For this question for C++ , it was:

    vector<int> twoSum(vector<int>& nums, int target) {  }
    |__________|
         |
         v
    Return type for this function
    

    Dont change the above function prototype. The function implies that it expects a vector of type int as the return value. Let me know if you need more clarification


  • 0
    G

    Thank you, but what type of variable would 'indices' be?


  • 0
    A

    The comment section doesn't let me post any code with formatting. I have edited the original answer. Please look at my answer above for the updates.


Log in to reply
 

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