【Leetcode】Majority Element
2015-12-01 11:09
453 查看
题目链接:https://leetcode.com/problems/majority-element/
题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
考研的时候王道数据结构习题上有这题,求主元素,原来王道是从leetcode抄的 = =
算法:
题目:
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.
思路:
考研的时候王道数据结构习题上有这题,求主元素,原来王道是从leetcode抄的 = =
算法:
// 采用抵消的思路 public int majorityElement(int[] nums) { int mje = 0, count = 0; for (int i = 0; i < nums.length; i++) { if (count == 0) { mje = i;// count为0的时候,令当前值为主元素 count++; } else { // 当前有候选主元素的时候 if (nums[mje] != nums[i]) {// 抵消非候选主元素 count--; } else { count++; } } } return nums[mje]; }
相关文章推荐
- 【理解】iOS开发之UITableView详解
- Debian8环境搭建freeswitch 1.7测试视频混屏效果
- mobile framework
- c++字符串处理函数
- 深入理解Hadoop集群和网络
- Swift 数组
- 关于 Spring 中使用 context:property-placeholder 属性占位符设置配置文件
- Discuz/X3.1去掉标题中的Powered by Discuz!以及解决首页标题后的"-"
- Java的getClass()
- Android display架构分析
- 理解Angular中的$apply()以及$digest()
- ESP8266和msp430g2553的实践项目
- 图片上传之前预览
- 运用vertical:middle 使得元素垂直居中
- c# windows服务 一个进程 多个服务的使用
- Android列表ListView用NotifyDataSetChanged实现动态更新
- 这是霄哥的天气预报,屌不屌?
- SSKeychain
- JavaScript基础——定义变量
- php+mysql将大数据sql文件导入数据库