lintcode--主元素
来源:互联网 发布:ubuntu emacs 编辑:程序博客网 时间:2024/09/21 06:36
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
给出数组[1,1,1,1,2,2,2],返回 1
public class Solution {
/**
* 第二种方法 时间复杂度为O(n),空间复杂度为O(1)
//因为主元素个数至少大于等于数组元素的一般
//所以先nums[0]赋值给temp,再遍历数组,若等于temp,则n++,否则n--,
当n=0时交换temp的值并把n置1。
//最后的temp就是主元素。
*/
public int majorityNumber(ArrayList<Integer> nums){
int n = 1;//计数
int temp = nums.get(0);//先赋值给date,
for(int i =1;i<nums.size();i++){//再遍历数组
if(temp == nums.get(i)){//若等于temp,则n++,
n++;
}else{
n--;//不相同否则--
}
if(n == 0){//当n=0时交换temp的值并把n置1。
temp = nums.get(i);//
n =1;
}
}
return temp;//当n不为0的时候的数
}
}
- Lintcode 主元素
- LintCode-主元素
- 主元素(LintCode)
- lintcode 主元素
- 主元素-----lintcode
- LintCode:主元素 III
- LintCode 主元素
- lintcode ----主元素
- LintCode(easy)主元素
- lintcode,主元素
- LintCode 主元素
- LintCode :主元素
- Lintcode 主元素 III
- LintCode 46 主元素
- [Lintcode]主元素
- Lintcode 主元素
- lintcode--主元素
- [LintCode]46.主元素
- 值传递与引用传递
- Kibana汉化
- 移动端开发点击按钮后出现闪烁的结局方法
- jquery系列教程3-DOM操作全解
- Qt 2D绘图
- lintcode--主元素
- php判断身份证是否合乎规定
- hibernate初学2之核心接口
- 欢迎使用CSDN-markdown编辑器
- jquery系列教程4-事件操作全解
- HorizontalScrollView嵌套RecyclerView横向展示不全
- POJ 2330 Watchcow(欧拉回路)
- c++ ;类的继承(二)
- [practice]cpp primer 1 script