「LeetCode每日一题」——169. 多数元素
169. 多数元素
链接:https://leetcode-cn.com/problems/majority-element/
难度:简单
题目
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
思路
这题的意思就是有一个数是超过了二分之一的,那我只有遇到不相同的数就删除,那么最后剩下的数一定是那个超过二分之一的。
方案代码
解法方法:
class Solution:
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
相关
原创文章,作者:flypython,如若转载,请注明出处:http://flypython.com/algorithm/leetcode/223.html
相关推荐
-
「LeetCode每日一题」—— 202. 快乐数
202. 快乐数 链接:https://leetcode-cn.com/problems/happy-number/难度:简单 题目 点击原文链接跳转查看题目 思路 今天是四月最后…
30/04/2020 -
「LeetCode每日一题」225. 用队列实现栈
LeetCode每日一题 周五跟大家预告了LeetCode每日一题的活动,今天活动已经开始了。打开leetcode中文版,你可以在题库中看到制定的题目,行动起来吧。 在这里帖下打卡…
01/03/2020 -
「LeetCode每日一题」—— 22. 括号生成
22. 括号生成 链接:https://leetcode-cn.com/problems/generate-parentheses/难度:中等 题目 数字 n 代表生成括…
09/04/2020 -
「LeetCode每日一题」—— 1111. 有效括号的嵌套深度
1111. 有效括号的嵌套深度 链接:https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-par…
01/04/2020 -
「LeetCode每日一题」—— 33. 搜索旋转排序数组
33. 搜索旋转排序数组 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/难度:中等 题目 点…
27/04/2020 -
「LeetCode每日一题」—— 55. 跳跃游戏
55. 跳跃游戏 链接:https://leetcode-cn.com/problems/jump-game/难度:中等 题目 思路 这题很容易想到从后面开始往前面跳。如果倒数第一…
17/04/2020 -
「LeetCode每日一题」—— 466. 统计重复个数
466. 统计重复个数 链接:https://leetcode-cn.com/problems/count-the-repetitions/难度:困难 题目 思路 这是一道困难题,…
19/04/2020 -
「LeetCode每日一题」—— LOCF.51. 数组中的逆序对
LOCF.51. 数组中的逆序对 链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/难度:中等 …
24/04/2020 -
「LeetCode每日一题」——322. 零钱兑换
322. 零钱兑换 链接:https://leetcode-cn.com/problems/coin-change/难度:中等 题目 给定不同面额的硬币 coins 和一个总金额 …
08/03/2020 -
「LeetCode每日一题」——999. 车的可用捕获量
999. 车的可用捕获量 链接:https://leetcode-cn.com/problems/available-captures-for-rook/难度:简单 题目 在一个 …
26/03/2020
您必须登录才能发表评论。