lintcode-easy-Majority Number
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Majority Number相关的知识,希望对你有一定的参考价值。
Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
Challenge
O(n) time and O(1) extra space
投票法,利用一下要找的这个数大于size的一半这个性质
public class Solution { /** * @param nums: a list of integers * @return: find a majority number */ public int majorityNumber(ArrayList<Integer> nums) { // write your code if(nums == null || nums.size() == 0) return 0; Integer result = null; int count = 0; for(int i = 0; i < nums.size(); i++){ if(result == null){ result = nums.get(i); count = 1; } else if(nums.get(i) == result){ count++; } else{ count--; if(count == 0){ result = nums.get(i); count = 1; } } } return result; } }
以上是关于lintcode-easy-Majority Number的主要内容,如果未能解决你的问题,请参考以下文章
R语言e1071包中的支持向量机:构建nu-classification类型的支持向量机SVM并分析不同nu值惩罚下模型分类螺旋线型(sprials)线性不可分数据集的表现