C++ solution with T(n)=O(n) but gives Last executed i/p Runtime error. Plzzzz, Help....!!!


  • 0
    K
    #define max 100000
    class Solution {
    public:
    	int temp,i,k,last;
    	int index_next;
    	bool ref_array[max];
    	std::vector<int> result;
        vector<int> twoSum(vector<int>& nums, int target) {
    	 	for(i=0; i<nums.size(); i++)
    	 	{
    	 		temp=target-nums[i];
    	 		if(abs(temp) >= 0 && ref_array[abs(temp)] == 1)
    		    {
    		    	last=target-nums[i];
    				while(nums[k]!=last)
    				{
    					k++;
    					index_next=k;
    				}
    		        result.push_back(index_next+1);
    	 			result.push_back(i+1);
    		    }
    		       ref_array[abs(nums[i])] = 1;
    	 	}
    	 	return result;
        }
    };

  • 0
    S

    Say nums is {1,4} and target is 3

    for i = 0, you set ref_array[1] = 1;

    for i = 1, your if condition is satisfied and you try to find 3 -4 = -1 in nums array but you don't have it in nums

    So you will just loop for ever and eventually hit some runtime error.


  • 0
    B

    You assume max=100000, but how about nums = {100001, 1} and target = 100002?


Log in to reply
 

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