1. 程式人生 > >Python刷題:簡單陣列(二)

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)