Python刷题:简单数组(二)

6. Plus One

    Given a non-negative integer represented asa non-empty array of digits, plus one to the integer. You may assume theinteger do not contain any leading zero, except the number 0 itself. The digitsare stored such that the most significant digit is at the head of the list.

    给定一个由非负整数组成的非空数字数组,为该整数进行加一运算。假定,除了数字0本身以外,所有的数字都不包含前导0(前置补位0)。最终的结果会被存储在列表之中,该数字的最高位存储于列表的首位。

示例:

给定[1,2,3,4]

返回[1,2,3,5]

问题分析:该题目的要求中最需要注意的是十进制表示下的9+1向上进位的操作问题,因此不能简单的把它划分为末尾加一问题,要在每次进行加一操作时,进行判定。

程序:

def PlusOne(nums):
	x = 0                                #偷懒式写法,先把位于数组中的各个位数字元素在x中组合为新的数字
	for i in nums:
		x = x * 10 +i
	return[int(y) for y in str(x + 1)]   #对这个数字进行加一操作后转化为字符串,然后遍历该字符串的每个字符,将其转化为整数,再
                                             #输出出去,从而实现向列表的转化

7. Merge Sorted Array

    Given two sorted integer arrays nums1 andnums2.Merge nums2 into nums1 as one sorted array.

    给定两个有序的整数数组nums1和nums2。将num2融合到nums1中,组成一个新的有序数组。

示例:

给定:nums1 = [1,2,3,4]

     nums2 = [2,3,4,5]

返回:nums1 =[1,2,2,3,3,4,4,5]

问题解析:该问题本质上就是按顺序遍历,将nums2中的元素排序至nums1中。

程序:

def MergeArray(nums1, nums2):
	m = len(nums1)
	n = len(nums2)
	i = 0
	j = 0
	nums = []
	while i < m and j < n:                               #在这里先把两者当中较短的一个数组先消耗完毕,使新的数组在这部分有序
		if(nums1[i] > nums2[j]):
			nums.append(nums2[j])
			j += 1
		else:
			nums.append(nums1[i])
			i += 1
	if(i == m):                                        #判断nums1、nums2中那一个还有元素剩余,将剩余的元素直接添加到新数组的尾部
		while(j < n):
			nums.append(nums2[j])
			j += 1
	else:
		while(i < m):
			nums.append(nums1[i])
			i += 1
	return(nums)

8.Pascal’s Triangle

    Given numRows, generate the first numRows ofPascai’s triangle.

    给排数,生成一个与该排数相同的杨辉(帕斯卡)三角列表。

示例

给定numRows = 3

得到:[ [1], [1,1], [1, 2, 1]]

题目解析:题目要求就是要生成类似于杨辉三角的数组,我们知道,对于杨辉三角,两边线的数字全部为1,而边线内的数字为上一层级与其成倒三角位置的两个数字之和,只要依照规律逐步运算即可。当然,一个有趣的规律是对于第二行[1, 1],将其扩展为[0, 1,1]与[1, 1, 0],两者相加得到第三行[1, 2, 1],该规律可以以此向下类推。在此处,采取常规方法演示,在第九题中,使用简单方法演示。

程序:

def gen(numRows):
	if numRows == 0:                                                #如果给定行数为零,返回空列表
		return [] 
	tri = [[1]]                                                     #如果给定行数不为零,先把列数为1的基础列表给出
	for i in range(1,numRows):                                      #逐行创建列表内的列表,类似于二维数组
		j = 
		x = []                                                  #x为新的一行列表数据的存储列表,当其数据收集完毕后再添加至
                                                                        #输出列表
		while(j < i+1):
			if(j == 0 or j == i ):                          #每行中的首尾元素都为1
				x.append(1)
			else:
				x.append(tri[-1][j-1] + tri[-1][j])     #除了首位元素,其他元素由上一行元素进行加法运算得出
			j += 1
		tri.append(x)
	return(tri)

9.Pascal’s Triangle Ⅱ

    Given an index K, return the Kth row of thePascal’s triangle. Note: Could you optimize your algorithm to use only O(K)extra space?

    给定一个索引数K,返回杨辉三角的第K行数据。注意:你是否可以实现你的算法只用到符合O(K)要求的额外空间?

示例:

给定K = 3

返回[1, 3, 3, 1].

题目解析:如第八题所示

程序:

def getRow(rowIndex):
    res = [1]
    for i in range(1, rowIndex + 1):
        res = list(map(lambda x, y: x + y, res + [0], [0] + res))  #如果给定map两个可迭代变量,跟他就会按顺序遍历两个变量,将其对应
                                                                   #元素应用于map的函数参数当中
    return(res)

10.Best Time to Buy and SellStock

    Say you have an array for which the ithelement is the price of a given stock on day i. If you were only permitted tocomplete at most one transaction(ie, buy one and sell one share of the stock),design an algorithm to find the maximum profit.

    给定一个数组,该数组中的第i个元素表示给定的股票在第i天内的价格。如果你只被允许最多进行一次交易(即:购买一次并出售一次,或者不进行任何操作),设计一个算法找出你的最大收益。

示例:

(1)给定[7, 1, 5, 3, 6, 4],输出5

(2)给定[7, 6, 4, 3, 1],输出0

题目解析:根据题目要求,我们要找出数组中两元素间最大的正数差值,且该元素对中索引大的元素必须为被减数。如果不存在要求的正数差值,就返回0。

程序:

def sell(prices):
	current_profit = max_profit = 0
	for i in range(1, len(prices)):                                                   #使用该结构遍历数组
		current_profit = max(0, current_profit + prices[i] - prices[i-1])         #不断地计算累计临近元素间的差值,只要
                                                                                          #结果大于零,不会遗漏任何值
		max_profit = max(current_profit, max_profit)                              #记录已累计差值中的最大值,防止遗失
	return(max_profit)






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值