LeetCode Blog for course "Algorithms" -- Problem 1 & 2

来源:互联网 发布:家庭用网络交换机 编辑:程序博客网 时间:2024/06/07 02:40
Problem 1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

My solution in Python:


 1 2 3 4 5 6 7 8 910
class Solution(object):    def twoSum(self,nums,target):        first=0        second=0        for x in range(0,len(nums)):            for y in range(x+1,len(nums)):                if nums[x]+nums[y]==target:                    first=x                    second=y                    return [first,second]



Review:

We use nested iterations here. For each number in the array, we go through the numbers in the array after it to see if there is a required match. Because there is only one such pair that suits the requirement (add up to a specific target), once we find such a match, we can stop the iteration here.





Problem 2. Add Two Numbers



You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

My solution in Python:


 1 2 3 4 5 6 7 8 910111213141516171819202122232425
class Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        answer = ListNode(0);        pointer = answer;        carry = 0;        while True:            if l1 != None:                carry += l1.val;                l1 = l1.next;            if l2 != None:                carry += l2.val;                l2 = l2.next;            pointer.val = carry % 10;            carry /= 10;            if l1 != None or l2 != None or carry != 0:                pointer.next = ListNode(0);                pointer = pointer.next;            else:                break;        return answer;


Review:

Given that the digits are stored in reverse order in the list, the first node in the list is the least significant bit in the integer, so we can add the two lists directly from the first node to the last node. The solution is very straight-forward. Note that along with checking whether both l1 and l2 have reached their ends, we also must check whether the carry bit equals 0. A non-zero carry bit must be carried to the next iteration and have a new node in the answer list to store it. When both l1 and l2 have reached their end, and the carry bit is 0, the algorithm ends.