【LeetCode】Python之旅 1-2

#由于是starter,参考大神的python解法(http://vimersu.win/blog/2014/03/20/leetcode-solution-02/ 作者: Vimer Su)并另做详细阐述

1.Two Sum

题意:给定一个target值,如果数组中的两个数t1、t2相加为target,返回这两个数在数组中的下标。(下标从0开始)

分析:使用一个字典保存数组的值及其下标(形成键值对),遍历数组nums[],如果字典键target-nums[i]的值不存在,则保存其下标;存在则说明t1已经被找到,且目前i指向t2的下标,返回t1的字典值和i即可

代码:

 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         dict={}
 4         for i in range(len(nums)):
 5             if dict.get(target-nums[i],None) == None:
 6                 dict[nums[i]] = i
 7             else:
 8                 return (dict[target-nums[i]],i)
 9 
10 p=Solution()
11 nums=[2,7,11,15]
12 target=9
13 p.twoSum(nums,target)

 

2.Add Two Numbers

其实感觉这个比上题还简单一些~

题意:例如,一个链表保存2->4->3,一个链表保存5->6->4,输出342+564=807即7->0->8,数字都是倒序

分析:对位相加,设置进位位,重点在于如何写单链表

代码:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6         
 7 class Solution:
 8     # @return a ListNode
 9     def addTwoNumbers(self, l1, l2):
10         nHead, flag = ListNode(0), 0
11         head = nHead
12         while flag or l1 or l2:
13             node = ListNode(flag)
14             if l1: 
15                 node.val += l1.val
16                 l1 = l1.next
17             if l2: 
18                 node.val += l2.val
19                 l2 = l2.next
20             flag = node.val // 10
21             node.val %= 10
22             head.next, head = node, node
23         return nHead.next

这题很久才AC,后来问了小若然,原来头部对于链表class的注释不要删...不然就会抛出异常(Exception: Type <class '__main__. '>: Not implemented),它这个只是告诉你它的测试平台就是这么定义的。然后也并不需要自己写测试代码(这可能也是为什么我写了测试代码print会打印两遍的原因),后台会自动调用你写的这个类的(因此也千万不要改掉它的类名)。对此,小若然表示这很leetcode,就是这样对新手不友好TAT

2+.第2题的改编,即如果链表顺序是3->4->2和4->6->5,则需要先将链表逆序再相加,才能保证从低位向高位运算,关键在于单链表逆序的reverse函数,参考http://blog.csdn.net/u011608357/article/details/36933337

代码:

 1 class ListNode(object):
 2     def __init__(self, x):
 3         self.val = x
 4         self.next = None
 5 
 6 
 7 def reverse(head):
 8     if head is None or head.next is None:
 9         return head
10     pre = None
11     cur = head
12     h = head
13     while cur:
14         h = cur
15         tmp = cur.next
16         cur.next = pre
17         pre = cur
18         cur = tmp
19     return h
20 
21 
22 class Solution(object):
23     def addTwoNumbers(self, l1, l2):
24         newl1=reverse(l1)
25         newl2=reverse(l2)
26         nHead, flag = ListNode(0), 0
27         head = nHead
28         while newl1 or newl2 or flag:
29             node = ListNode(flag)
30             if newl1:
31                 node.val += newl1.val
32                 newl1 = newl1.next
33             if l2:
34                 node.val += newl2.val
35                 newl2 = newl2.next
36             flag = node.val // 10
37             node.val %= 10
38             head.next, head = node, node
39         newHead = reverse(nHead)
40         print newHead.val
41         print newHead.next.val
42         print newHead.next.next.val
43 
44 l1 = ListNode(2)
45 l1.next = ListNode(4)
46 l1.next.next = ListNode(3)
47 l2 = ListNode(5)
48 l2.next = ListNode(6)
49 l2.next.next = ListNode(4)
50 p = Solution()
51 p.addTwoNumbers(l1, l2)

单链表逆置:把cur指向当前节点,pre指向前一节点,把cur.next保存到临时变量tmp,然后cur的next指向pre,然后pre取代现在的cur,cur指向tmp,继续循环此过程。另外注意h保存头结点。

 

今天看到知乎上轮子哥说可以按照通过率从高到低来做,觉得是个好主意...尤其对于我这样的python入门者来说。

344.Reverse String

 1 class Solution(object):
 2     def reverseString(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         length = len(s)
 8         s1 = []
 9         for i in range (0,length):
10             s1.append('0')
11         for i in s:
12             s1[length-1] = i
13             length -= 1
14         s1 = ''.join(s1)
15         return s1

这里主要记住一个,python中字符串和字符串数组的相互转换方法:

字符串数组转字符串:['x','y','z'] => 'xyz'

b = ''.join(['x','y','z'])

字符串转字符串数组:'xyz' => ['x','y','z']

a = list('xyz')

 

posted @ 2016-07-07 10:06  Rivrr  阅读(841)  评论(0编辑  收藏  举报