《高级编程技术》第九周作业

1.Move Zeroes

题目概述:

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.


解题思路:

首先,对nums列表进行遍历,并使用 count 变量记录nums中0的个数,当nums[i] 为0时,count+1, 并从nums中删去nums[i]。

然后,再用append函数从nums尾部添加count个数的0.


代码如下:

class Solution:
	def moveZeroes(self, nums):
		count = 0
		while(True):
			if 0 in nums:
				nums.remove(0)
				count += 1
			else:
				break
		for i in range(count):
			nums.append(0)

1.Toeplitz Matrix

题目概述:

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
 

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512

In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.


解题思路:

对matrix进行遍历,比较matrix[i][j]和matrix[i+1][j+1]的值,如果不同,则返回False。


代码如下:

class Solution:
	def isToeplitzMatrix(self, matrix):
		for i in range(len(matrix)-1):
			for j in range(len(matrix[i])-1):
				if matrix[i][j] != matrix[i+1][j+1]:
					return False
		return True

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/80217567