3个月用python刷完leetcode600题!-数组简单题(二)

浏览: 2534

十五天的时间,刷完了所有的简单题,避免遗忘,所以开始简单题的二刷,第一遍刷题的时候过得速度比较快,因为我觉得基础不好的我,不要硬着头皮去想最优的方法,而是应该尽量去学一些算法思想,所以每道题只给自己5-10分钟的时间想,想不出来的就去找相关的答案,所以刷的比较快。二刷的时候按照leetcode官方给出的题目分类展开,同时,将解题思路记录于简书加深印象。
想要一起刷题的小伙伴,我们一起加油吧!
我的github连接:https://github.com/princewen/leetcode_python

169、Majority Element

Majority Element


注意最多的元素出现的次数大于数组长度的一半,所以使用如下的代码,在最极端的情况下,最后的count都会大于0,cand就是所要找的元素

class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

cand = nums[0]
count = 1
for i in nums[1:]:
if count == 0:
cand, count = i, 1
else:
if i == cand:
count = count + 1
else:
count = count - 1
return cand

189、Rotate Array

Rotate Array


直接拼接数组:

class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""

n = len(nums)
nums[:] = nums[n - k:] + nums[:n - k]

217、Contains Duplicate

Contains Duplicate


利用set不能保存重复元素的特性,判断前后两个数组长度是否相同即可:

class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""

n = len(nums)
nums[:] = nums[n - k:] + nums[:n - k]

219、 Contains Duplicate II

Contains Duplicate II


仍然用dict保存数组元素出现的位置,两种情况下更新:

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""

dic = dict()
for index,value in enumerate(nums):
if value in dic and index - dic[value] <= k:
return True
dic[value] = index
return False

268. Missing Number

Missing Number


利用数学公式进行求解即可:

class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

n = len(nums)
return n * (n+1) / 2 - sum(nums)

283. Move Zeroes

Move Zeroes


遍历数组,用一个变量记录当前不为0的个数,同时也是新不为零元素插入的位置:

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""

index = 0
for num in nums:
if num != 0:
nums[index] = num
index += 1
for i in range(index,len(nums)):
nums[i] = 0

414. Third Maximum Number

Third Maximum Number


这里用三个值记录前三大的数字,要注意是三个不同的数字,重复的数字不记录排序,所以要注意判断条件:

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

max1 = max2= max3=None
for num in nums:
if num > max1:
max2,max3 = max1,max2
max1=num
elif num > max2 and num < max1:
max2,max3= num,max2
elif num > max3 and num < max2:
max3 = num
return max1 if max3==None else max3

448. Find All Numbers Disappeared in an Array

Find All Numbers Disappeared in an Array


这个题就比较神奇了,注意到数组元素个数跟元素范围是一样的,所以我们可以把出现过的元素对应下标位置的数字变成负数,最后把所有正数对应的下标拿出来,就是缺失的数字。

class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""

for i in range(len(nums)):
index = abs(nums[i]) - 1
nums[index] = -abs(nums[index])
return [i + 1 for i in range(len(nums)) if nums[i] > 0]

485. Max Consecutive Ones

Max Consecutive Ones


求数组中连续的1的最多个数,遍历数组即可:

class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

cnt = 0
ans = 0
for num in nums:
if num == 1:
cnt = cnt + 1
ans = max(ans,cnt)
else:
cnt = 0
return ans

532. K-diff Pairs in an Array

K-diff Pairs in an Array


如果k大于0,则返回两个set的交集
如果k=0,则计数,找出出现1次以上的元素的个数
如果k小于0,返回0

class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""

if k>0:
return len(set(nums) & set(n+k for n in nums))
elif k==0:
return sum(v>1 for v in collections.Counter(nums).values())
else:
return 0

561、Array Partition I

Array Partition I


就是返回排序后第1,3,5,。。2n-1小的数

class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

return sum(sorted(nums)[::2])

566. Reshape the Matrix

Reshape the Matrix


将数组转换为1行,然后根据要转换的行列数进行转换

class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""

if len(nums) * len(nums[0]) != r * c:
return nums
else:
onerow = [nums[i][j] for i in range(len(nums)) for j in range(len(nums[0]))]
return [onerow[t * c:(t + 1) * c] for t in range(r)]

581、Shortest Unsorted Continuous Subarray

Shortest Unsorted Continuous Subarray


all_same[::-1]返回的不是从正向数的索引,返回的是以最后一个元素为0索引,倒数第二个元素为1索引的反向数列的索引值:

class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

all_same = [a == b for (a, b) in zip(nums, sorted(nums))]
return 0 if all(all_same) else len(nums) - all_same.index(False) - all_same[::-1].index(False)

如果你喜欢我写的文章,可以帮忙给小编点个赞或者加个关注,我一定会互粉的!
如果大家对leetcode感兴趣,欢迎跟小编进行交流,小编微信为sxw2251,加我要写好备注哟!:

我的微信

推荐 0
本文由 石晓文 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册