[LeetCode][数论]Majority Element
来源:互联网 发布:淘宝网羽绒棉裤女 编辑:程序博客网 时间:2024/06/13 19:49
题目描述:
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.
思路:
前提条件:数据中有一个元素出现的个数超过数组长度的一半,求出这个元素
过程:要找出数组中出现个数最多的元素,遍历和计数是一定的,最基本的是HashMap存储,但能不能节省一点存储空间呢?因为题目给定的是出现的个数超过其他所有的数字,所以可以采用一个标记元素,记录一个数据,策略是:如果元素i是记录下来的数据,计数加一;如果当前计数为0,说明之前不存在出现超过数据长度二分之一的数字,重复将当前元素赋值给标记元素,计数为1;如果元素i既不是当前记录元素,计数值也不为0,则应该将计数减一,抵消依次出现的次数,最后,返回当前记录元素
代码实现:
public class Solution { public int majorityElement(int[] nums) { if(nums.length == 1){ return nums[0]; } int m1 = nums[0]; int c1 = 0; for(int i = 0; i<nums.length; i++){ int x = nums[i]; if(x == m1) ++c1; else if(c1 == 0){ m1 = x; c1 = 1; }else{ --c1; } } return m1; }}
0 0
- [LeetCode][数论]Majority Element
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Bag of Features (BOF)图像检索算法
- java io exception Broken Pipe
- iOS的socket开发基础
- KVO的概述与使用
- 获取DeviceToken值,iOS推送
- [LeetCode][数论]Majority Element
- fir.im Weekly - 人人都需要的 IT 技能图谱
- css3 flex的使用示例集合
- 推荐初学者Java Web入门笔记及实例
- Google cardBoard Android API (十五):两个接口中的CardboardView.Renderer
- [UnityUI]UGUI射线检测
- 从底层看android5.0系统的启动过程
- idea15.0.4 jfinal配置启动
- 微信公众帐号开发教程第4篇-各种消息的接收与响应