Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepy
class Solution:
	def mergeTwoLists(self, l1, l2):

		result = ListNode(0) # The new list we are going to eventually return
		head = result # keep a pointer to the head so we can return head.next in the end
		while(l1 != None and l2 != None): # This check is important in the case where one list is shorter than the other
			if l1.val < l2.val: # Add l1's value as a new node to result if its less than l2's
				result.next = ListNode(l1.val)
				l1 = l1.next
				result = result.next
			elif l2.val < l1.val: # Add l2's value as a new node to result if its less than l1's
				result.next = ListNode(l2.val)
				l2 = l2.next
				result = result.next
			else: # In this case, the values must be equal so add both to result and move the linked lists forward
				result.next = ListNode(l1.val)
				result = result.next
				result.next = ListNode(l2.val)
				result = result.next
				l1 = l1.next
				l2 = l2.next

		if l1 == None and l2 != None: # If l2 is longer than l1, add all of the remaining values of l2 to result
			while(l2 != None):
				result.next = ListNode(l2.val)
				result = result.next
				l2 = l2.next
		elif l2 == None and l1 != None: # if l1 is longer than l2, add all of the remaining values of l1 to result
			while(l1 != None):
				result.next = ListNode(l1.val)
				result = result.next
				l1 = l1.next

		return head.next # return the result


Remove Duplicates from Sorted Array

Code Block
class Solution(object):
    def removeDuplicates(self, nums):
        if not nums:
            return 0
        
        i = 1
        bound = len(nums)
        prev = nums[0]
        
        while i < bound:
            if prev == nums[i]:
                nums.pop(i)
                bound = len(nums)
            else:
                prev = nums[i]
                i += 1
        
        return len(nums)