Given an array of size n, find the majority element. The majority element is the element that appear
2016-04-20 14:18
591 查看
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
=============================================
public class Solution {
public int majorityElement(int[] nums) {
int flag=nums[0];
int count=1;
for(int i=1;i<nums.length;i++){
if(count==0){
count ++;
flag=nums[i];
}else if(flag==nums[i]){
count++;
}else{
count--;
}
}
return flag;
}
}
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
=============================================
public class Solution {
public int majorityElement(int[] nums) {
int flag=nums[0];
int count=1;
for(int i=1;i<nums.length;i++){
if(count==0){
count ++;
flag=nums[i];
}else if(flag==nums[i]){
count++;
}else{
count--;
}
}
return flag;
}
}
相关文章推荐
- Android初学习 - Activity启动模式(lauchMode)总结
- Android初学习 - Service 中的 onStart 和 onStartCommand
- unity 实现流光效果
- unity 实现流光效果
- Android上层访问HAL层(呼吸灯测试代码)
- Android布局RelativeLayout(相对布局)详解
- ios开发多线程篇——GCD的基本使用
- iOS之在写一个iOS应用之前必须做的7件事(附相关资源)
- iOS获取屏幕亮度和调整屏幕亮度的方法
- Android自定义View读取XML属性详解
- Android初学习 - onNewIntent()触发机制及注意事项
- Android DiskLruCache缓存完全解析(网易新闻)
- android 批量处理列表
- Android Studio 2.0和Android Studio 2.1 Beta 3下载分享
- adb获取android手机系统版本,已对应的api版本和硬件相关信息
- 判断App是不是第一次启动
- android 自己的思路写的订单管理界面
- android studio+Droid4x(海马玩)
- block没那么难(三):block和对象的内存管理
- Android Scrollview 内部组件android:layout_height="match_parent"无效的解决办法