169. Majority Element

来源:互联网 发布:社交网络数据挖掘 pdf 编辑:程序博客网 时间:2024/06/05 12:47
  public static int majorityElement(int[] nums) {        if(nums == null || nums.length == 0) {            return 0;        }        int count = 0;        int number = nums[0];        for(int i = 0; i < nums.length; i++) {            if(number == nums[i]) {                count++;            }else if(count == 0){                number = nums[i];                count++;            }else {                count--;            }        }        count = 0;        for(int i = 0; i < nums.length; i++) {            if(number == nums[i]) {                count++;            }        }        if(count >= (nums.length/2)) {            return number;        }else {            return 0;        }    }
0 0