HELP! Help me find the bug of my code (C++), please! orz


  • 0
    L

    I encountered Runtime Error for a specific test case, but when I test my code using this test case (using 'Run code'), it produced the correct output. Why? Where is the bug?
    FAQ said it may have some Undefined Behaviors. Can you help me find it? Thank you!!!

    Specific test case:
    [21,27,83,67,10,62,52,49,5,50,4,99,87,74,70,6,88,62,27,39,91,96,60,35,22,12,71,56,44,19,6,63,67,90,70,60,52,5,57,40,98,61,49,38,12,57,47,24,38,52,42,61,54,8,66,66,16,68,71,23,24,75,27,73,65,57,29,64,84,91,60,86,11,16,80,85,91,62,36,18,61,60,92,91,15,78,19,46,17,29,3]
    [47,32,80,7,66,90,39,41,76,81,66,63,90,30,14,10,69,0,0,54,81,59,73,76,41,3,68,56,75,76]

    My code

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            if (!(nums1.size())) return nums1;
            if (!(nums2.size())) return nums2;
            int nums1_max = *max_element(nums1.begin(),nums1.end());
            int nums2_max = *max_element(nums2.begin(),nums2.end());
            int n1 = nums1.size(), n2 = nums2.size();
            int standard = (n1 > n2 ? n1 : n2) + 1;
            int table_size = nums1_max > nums2_max ? nums1_max : nums2_max;
            int* table = new int[table_size]();
            
            for (int i = 0; i < n1; i++)
            {
                if (table[nums1[i]]) table[nums1[i]]++;
                else table[nums1[i]] = standard + 1;
            }
            for (int i = 0; i < n2; i++)
            {
                table[nums2[i]]--;
            }
            
            vector<int> intersection;
            for (int i = 0; i < table_size; i++)
            {
                if (table[i] == standard) intersection.push_back(i);
            }
            
            return intersection;
        }
    };
    

Log in to reply
 

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