LeetCode__169. Majority Element
2016-01-11 21:02
375 查看
169. 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.
如题,给定一个数组,找出其中元素个数超过一半的数,
本来写不好,但是后面有一个假设,及这样的数数组中一定存在,这样难度就大大降低了。
借鉴了上一个程序:
public class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1) return nums[0];
Arrays.sort(nums);
int sum = 1;
for(int i = 0; i <nums.length-1; i++){
if(nums[i]==nums[i+1]){
sum++;
}else{
sum = 1;
}
if(sum>nums.length/2){
return nums[i];
}
}
return nums[0];//这个我不想加,但是必须要返回值,所以……
}
}
很简单了……
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.
如题,给定一个数组,找出其中元素个数超过一半的数,
本来写不好,但是后面有一个假设,及这样的数数组中一定存在,这样难度就大大降低了。
借鉴了上一个程序:
public class Solution {
public int majorityElement(int[] nums) {
if(nums.length==1) return nums[0];
Arrays.sort(nums);
int sum = 1;
for(int i = 0; i <nums.length-1; i++){
if(nums[i]==nums[i+1]){
sum++;
}else{
sum = 1;
}
if(sum>nums.length/2){
return nums[i];
}
}
return nums[0];//这个我不想加,但是必须要返回值,所以……
}
}
很简单了……
相关文章推荐
- 蓝桥杯 ALGO-92 前缀表达式
- 递归算法的时间复杂度终结篇
- xcode simulator不显示具体版本/解决xcode多个模拟器的办法
- 【JDK源码分析】String的存储区与不可变性(转)
- Android 进行单元測试难在哪-part3
- cdh完美集成kafka
- android ui
- Tengine笔记1:安装Tengine和Tengine说明
- 一个简单的爬虫(1)
- android adapter getChildAt(int)方法使用
- 聚合函数与分组
- 批处理命令--管道&条件判断
- 004_在Eclipse环境下搭建Android开发平台(离线搭建)
- Fragment使用小结
- Firemonkey使用iOS的第三方静态库(Link Binary With Libraries)
- Java IO的RandomAccessFile的使用(转)
- Android收藏商品/关注商品
- C# Devexpress 中控件的一些使用技巧
- java代码中一些要注意的语法应用
- nyoj 223 Drainage Ditches 【网络流&&最大流】