周刷题第一期总结(two sum and two numbers)

由于深深的知道自己是事件驱动型的人,一直想补强自己的薄弱环节算法,却完全不知道从哪里入手。所以只能采用最笨的办法,刷题。从刷题中遇到问题就解决问题,最后可能多多少少也能提高一下自己的渣算法吧。

暂时的目标是一周最少两道,可能会多做多想,工作再忙也会完成这个最低目标。

 

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

这道题拿到手,感觉还算有点思路。

要做到O(n)的算法复杂度,肯定最多遍历一遍数组从这个思路入手,大概能想到记录数字的出现,以及用目标减去记录数字,同时拿到其索引的思路

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        look_up = {}
        for i, num in enumerate(nums):
            if target-num in look_up:
                return [look_up[target-num], i]
            look_up[num] = i
        return

造一个字典,用这个字典的key记录出现的数字,用value记录其出现的索引位置。然后使用target - num 用目标数字减去当前遍历到的数字的结果有没有在look_up里面有key记录,如果有读取其索引 然后 带上现在遍历到的数字索引返回。

 

 Add Two Numbers:

You are given two linked lists representing two non-negative numbers. 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.

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

这道题首先我读了半天题才理解到题意。要弄出这道题首先你要知道python里面链表一般如何实现,所以就需要去补充一些链表的知识(事件驱动学习就是这个意思)。查找了一些资料之后理解了链表再来看这道题就明白了

首先实现一个ListNode

class Solution(object):
    ListNode(self, val):
        self.val = val
        self.next = None

每当我们新开一个链表,就相当于又多创建一个类似ListNode结构的object。self.next存储的是下一个链表的地址。

这道题其实考察的是使用链表进行大数相加,由于从个位加起,所以是反转存储的方便进位。下面看代码

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy, carry = ListNode(0), 0
        current = dummy

        while l1 or l2:
            val = carry
            if l1:
                val += l1.val
                l1 = l1.next
            if l2:
                val += l2.val
                l2 = l2.next
            carry, val = val / 10, val % 10
            current.next = ListNode(val)
            current = current.next

        if carry == 1:
            current.next = ListNode(1)

        return dummy.next

carry 代表进位的意思,dummy是初始化的存储结果链表中的头部指针,赋给current同样地址,但是current会在随后的操作中被往后移动。

其余的都很简单了。

 

第一次开始刷题,感觉不是特别习惯,也没有相关的思维。 希望万事开头难经后可以熟练起来。

 

posted @ 2016-10-24 01:18  piperck  阅读(377)  评论(0编辑  收藏  举报