Python 刷Leetcode题库,顺带学英语单词(40)

简介: Python 刷Leetcode题库,顺带学英语单词(40)

Majority Element


Given an array of size n, find the majority element. The majority element is the element that appears more than [n/2] times.


You may assume that the array is non-empty and the majority element always exist in the array.     [#169]

Examples:
Input: [3,2,3]
Output: 3
Input: [2,2,1,1,1,2,2]
Output: 2


题意:找出数组中出现次数大于数组长度一半的元素  

 

>>> n=[3,2,3]
>>> [i for i in n if n.count(i)>len(n)//2][0]
3
>>> n=[2,2,1,1,1,2,2]
>>> [i for i in n if n.count(i)>len(n)//2][0]
2




Majority Element II


Given an integer array of size n, find all elements that appear more than [n/3] times.

Note: The algorithm should run in linear time and in O(1) space.


Examples:
Input: [3,2,3]
Output: [3]
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

题意:找出数组中出现次数大于数组长度三分之一的元素  

>>> n=[3,2,3]
>>> list({i for i in n if n.count(i)>len(n)//3})
[3]
>>> n=[1,1,1,3,3,2,2,2]
>>> list({i for i in n if n.count(i)>len(n)//3})
[1, 2]
>>>
目录
相关文章
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
38 6
|
1月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
65 2
|
29天前
|
算法
LeetCode第58题最后一个单词的长度
LeetCode第58题"最后一个单词的长度"的解题方法,通过从字符串末尾向前遍历并计数非空格字符,直接得出最后一个单词的长度。
LeetCode第58题最后一个单词的长度
|
1月前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
33 7
|
1月前
|
算法 Python
【Leetcode刷题Python】 LeetCode 2038. 如果相邻两个颜色均相同则删除当前颜色
本文介绍了LeetCode 2038题的解法,题目要求在一个由'A'和'B'组成的字符串中,按照特定规则轮流删除颜色片段,判断Alice是否能够获胜,并提供了Python的实现代码。
36 3
|
1月前
|
算法 Python
【Leetcode刷题Python】剑指 Offer 33. 二叉搜索树的后序遍历序列
本文提供了一种Python算法,用以判断给定整数数组是否为某二叉搜索树的后序遍历结果,通过识别根节点并递归验证左右子树的值是否满足二叉搜索树的性质。
14 3
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - II. 从上到下打印二叉树 II
本文提供了一种Python实现方法,用于层次遍历二叉树并按层打印结果,每层节点按从左到右的顺序排列,每层打印到一行。
28 3
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - I. 从上到下打印二叉树
本文介绍了使用Python实现从上到下打印二叉树的解决方案,采用层次遍历的方法,利用队列进行节点的访问。
28 2
|
1月前
|
Python
【Leetcode刷题Python】50. Pow(x, n)
本文介绍了LeetCode第50题"Pow(x, n)"的解法,题目要求实现计算x的n次幂的函数,文章提供了递归分治法的详细解析和Python实现代码。
14 1
|
1月前
|
Python
【Leetcode刷题Python】LeetCode 478. 在圆内随机生成点
本文介绍了LeetCode 478题的解法,题目要求在给定圆的半径和圆心位置的情况下实现在圆内均匀随机生成点的功能,并提供了Python的实现代码。
16 1