* Computer Science/Algorithm

1171. Remove Zero Sum Consecutive Nodes from Linked List

soicem 2021. 6. 3. 22:00

문제: https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/

 

Remove Zero Sum Consecutive Nodes from Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) {
        ListNode* node = head;
        
        ListNode* prev = new ListNode(-1001);
        ListNode* dummy = prev;
        prev->next = head;
        
        while(node){
            ListNode* curr = node;
            
            int s = 0;
            
            while(curr){
                s += curr->val;
                curr = curr->next;
                
                if(s == 0){
                    break;
                }
            }
            
            if(s == 0){
                prev->next = curr;
                node = prev->next;
            } else {
                prev = node;
                node = node->next;
            }
        }
        return dummy->next;
    }
};

Time complexity: O(N^2)

Space complexity: O(1)

 

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) {
        ListNode* dummy = new ListNode(0);
        
        dummy->next = head;
        
        unordered_map<int, ListNode*> pSums;
        
        ListNode* node = dummy;
        int pSum = 0;
        while(node){
            pSum += node->val;
            pSums[pSum] = node;
            
            node = node->next;
        }
        
        node = dummy;
        
        pSum = 0;
        while(node){
            pSum += node->val;
            node->next = pSums[pSum]->next;
            
            node = node->next;
        }
        
        return dummy->next;
    }
};

Time complexity: O(N)

Space complexity: O(N)

 

'* Computer Science > Algorithm' 카테고리의 다른 글

718. Maximum Length of Repeated Subarray  (0) 2021.08.28
351. Android Unlock Pattern  (0) 2021.08.28
1488. Avoid Flood in The City  (0) 2021.05.30
1314. Matrix Block Sum  (0) 2021.05.23
1007. Minimum Domino Rotations For Equal Row  (0) 2021.05.22