A C++ 52ms/Space O(1)/Time O(n)/Align and Compare solution with explanation


  • 2
    O
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 
    {
        // count length
        int a = 0;
        for(ListNode* node = headA; node; node = node->next) a++;        
        int b = 0;
        for(ListNode* node = headB; node; node = node->next) b++;        
        if(!a || !b) { return nullptr; }        
        
        // align to tail
        ListNode* longer  = (a > b)? headA: headB;
        ListNode* shorter = (a > b)? headB: headA;
        int shift         = std::abs(a - b);
        for(int i = 0; i < shift; i++) longer = longer->next;        
        	
        // compare aligned list
        while(longer && longer != shorter) longer=longer->next, shorter=shorter->next;
        return longer;
    }

  • -1
    K

    class Solution {
    public:
    int missingNumber(vector<int>& nums) {

        sort(nums.begin(), nums.end());
        
        for(int i = 0; i<nums.size(); i++)
        {
            if(nums[i] != i)
            return i;
        }
        return nums.size();
        
    }
    

    };


Log in to reply
 

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