LintCode是类似于LeetCode的数据结构刷题网站,为什么用LintCode呢?因为是中文的啊勒勒!!虽然练习一下英语阅读也是好的,但是写代码就已经让我脑壳痛了,还要我看英语?
[表情.gif]
本文的习题难度都是LintCode上最简单的,题目如下:
- 斐波纳契数列
- 反转一个3位整数
- 矩阵面积
- 旋转字符串
- 删除链表中的元素
1 斐波纳契数列
描述
查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
- 前2个数是 0 和 1 。
- 第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
思路:创建一个列表numList包含前两个数,列表最后两个数的和添加到numList的末尾。
代码如下:
class Solution:
"""
@param n: an integer
@return: an ineger f(n)
"""
def fibonacci(self, n):
# write your code here
numList = [0,1]
for i in range(n-2):
numList.append(numList[-2] + numList[-1])
return numList[n-1]
2 反转一个3位整数
描述
反转一个只有3位数的整数。
思路:创建一个空字符串c,将输入整数的倒数第i(i=1,2,...len)位加到c中。
代码如下:
class Solution:
"""
@param number: A 3-digit number.
@return: Reversed number.
"""
def reverseInteger(self, number):
b = str(number)
c = ''
for i in range(len(b)):
c = c+b[-(i+1)]
return int(c)
3 矩阵面积
描述
实现一个矩阵类Rectangle
,包含如下的一些成员变量与函数:
- 两个共有的成员变量
width
和height
分别代表宽度和高度。 - 一个构造函数,接受2个参数 width 和 height 来设定矩阵的宽度和高度。
- 一个成员函数
getArea
,返回这个矩阵的面积。
如下:
class Rectangle:
'''
* Define a constructor which expects two parameters width and height here.
'''
# write your code here
def __init__(self, width, height):
self.width = width
self.height = height
'''
* Define a public method `getArea` which can calculate the area of the
* rectangle and return.
'''
# write your code here
def getArea(self):
return self.width*self.height
4 旋转字符串
描述
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
思路:当偏移量大于字符串长度时,让偏移量对字符串长度取余。弹出字符串最后一个添加到字符串第一个位置。
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
# write your code here
if not offset: return
if not str: return
n = len(str)
offset = offset%n
for i in range(offset):
t = str.pop()
str.insert(0,t)
5 删除链表中的元素
描述
删除链表中等于给定值val
的所有节点。
给出链表1->2->3->3->4->5->3
, 和 val =3
, 你需要返回删除3之后的链表:1->2->4->5
。
代码如下:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param val: An integer
@return: a ListNode
"""
def removeElements(self, head, val):
# write your code here
if head is None:
return None
while head.val ==val:
head = head.next
if (head == None):
return None
pre = head
while pre.next is not None:
if pre.next.val == val:
pre.next = pre.next.next
else:
pre = pre.next
return head
以上就是这些啦。