Passed in VC++, Runtime Error in OJ


  • 0
    E
    class Solution {
    public:
    	vector<int> twoSum(vector<int> &numbers, int target) {
    		map<int, bool> m;
    		map<int, int> indexMap;
    		for (int i = 0; i<numbers.size(); ++i)
    		{
    			if (numbers[i]>target) continue;
    			if (m.count(target - numbers[i]) > 0)
    			{
    				vector<int> v;
    				v.push_back(indexMap[target - numbers[i]] + 1);
    				v.push_back(i + 1);
    				return v;
    			}
    			else
    			{
    				m[numbers[i]] = true;
    				indexMap[numbers[i]] = i;
    			}
    		}
    	}
    };
    

    Runtime error for input [5,75,25],100

    But it runs just fine in VC++


  • 0
    B

    One problem I see is that you need to return a vector<int> from this method. You have no return statements.


  • 0
    E

    Since the question guarantees exact 1 answer, not returning is fine.


  • 0
    B

    Note sure if I understand. The return type of this method is vector<int>, and OJ's test driver has to examine the returned vector<int> to check if test passed or failed. If you are not returning anything, what is returned back to the caller?
    Am I missing something?


  • 0
    E

    well there is a return inside an if statement. Because the question guarantees 1 answer, that if statement will sooner or later be true and return the result.
    I've found the problem. I thought numbers won't be negative.
    So after deleting this line:
    if (numbers[i]>target) continue;
    The answer is accepted. Because if you skip negative numbers then you might not have an answer.

    Nevertheless, the OJ has problems because this program does not fail on [5,75,25],100. It only fails on negative inputs.


  • 0
    B

    My bad, I totally missed that return inside the if statement.


Log in to reply
 

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