C# easy to understand - beats 71%


  • 0
    I

    It's not incredibly efficient, but it's simple and easy to understand.

    What we do it at every iteration we find the left pointer (which points to m + iteration) and the right pointer (which points to n - iteration).

    And then in place we swap the values of the two pointers.

        public ListNode ReverseBetween(ListNode head, int m, int n) {
    
            var currentIteration = 0;
            m--;
            n--;
            
            while (currentIteration < (n - m) /  2 + 1)
            {
                // Get the left pointer 
                var left = head;
                for(int i = 0; i< m + currentIteration; ++i)
                {
                    left = left.next;    
                }
                
                // Get the right pointer
                var right = head;
                for(int i = 0; i< n - currentIteration; ++i)
                {
                    right = right.next;    
                }
                
                // Swap the values
                var value = left.val;
                left.val = right.val;
                right.val = value;
                
                // Move along
                currentIteration++;
            }
            
            return head;
        }
    

Log in to reply
 

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