Fork me on GitHub

LeetCode刷题(Week1)

本系列介绍

  本系列是本人在准备秋招过程中开始刷题leetcode的一个自我约束的手段,每周进行更新,这周是第一周,尝试一下,后面会更系统的进行分类和创作。

Jewels and Stones(771)easy

Q : You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

解题思路 :这道题主要就是一个字符串的查询,首先把J字符串拆分开,然后对S进行遍历,每个字符在J中的,就对结果加1,最后就得到结果了。

具体代码如下:

1
2
3
4
5
6
7
8
class Solution(object):
def numJewelsInStones(self, J, S):
res = 0
j1 = set(J)
for i in S:
if i in j1:
res+=1
return res

Array Partition I(561)easy

Q : Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

解题思路 :这一题只要把数组排序,然后就可以配对,选小的那个,其实就是把0,2,4这些序列是偶数的选出来就解决了。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
class Solution:
def arrayPairSum(self, nums):
newnums = sorted(nums)
res=0;
count= 0;
for i in newnums:
if count%2 ==0:
res=res+i
count=count+1
return res

Reshape the Matrix(566)easy

Q : In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

解题思路 :这道题主要是把原数据拉成一行,然后reshape。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def matrixReshape(self, nums, r, c):
newnums= [y for x in nums for y in x]
nums2=[[0 for j in range(c) ] for i in range(r) ]
if len(newnums)!=(r*c):
return nums
else:
for i in range(r):
for j in range(c):
nums2[i][j]=newnums[i*c+j]
return nums2

Toeplitz Matrix(766)easy

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.

解题思路:判断对角线是否相等,就是判断a[i][j]和a[i+1][j+1]是否相等

具体代码如下:

1
2
3
4
5
6
7
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

本周小结

  本周是开始做leetcode的第一周,还有很多东西需要系统化的完善起来,做了几道easy的题目,代码也只上传了一部分到github,后面都会继续完善!一起加油!
github地址:https://github.com/HarryinGit3/myleetcode

一个努力向上的GISER
0%