zoukankan      html  css  js  c++  java
  • Java for LeetCode 229 Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

    解题思路:

    《编程之美》寻找发帖水王的原题,两次遍历,一次遍历查找可能出现次数超过nums.length/3的数字,(出现三次不同的数即抛弃),第二次验证即可。

    JAVA实现如下:

    public List<Integer> majorityElement(int[] nums) {
            		List<Integer> list = new ArrayList<Integer>();
    		if (nums == null || nums.length == 0)
    			return list;
    		int left = nums[0], right=nums[0];
    		int count1 = 1, count2 = 0;
    		for (int i = 1; i < nums.length; i++) {
    			if (nums[i] == left)
    				count1++;
    			else if(right==left){
    				right=nums[i];
    				count2=1;
    			}
    			else if(right==nums[i])
    				count2++;
    			else if(count1==0){
    				left=nums[i];
    				count1=1;
    			}
    			else if(count2==0){
    				right=nums[i];
    				count2=1;
    			}
    			else{
    				count2--;
    				count1--;
    			}
    		}
    		count1=0;count2=0;
    		for(int i=0;i<nums.length;i++){
    			if(nums[i]==left)
    				count1++;
    			else if(nums[i]==right)
    				count2++;
    		}
    		if(count1>nums.length/3)
    			list.add(left);
    		if(count2>nums.length/3)
    			list.add(right);
    		return list;
        }
    
  • 相关阅读:
    oracle plsql 统计
    oracle plsql 自定义异常
    oracle plsql 异常
    oracle 游标
    oracle 存储函数,更新库存
    oracle TRUNC()函数
    plsql 的三种循环
    plsql if
    plsql 记录型变量
    CAS示例环境部署及配置
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4810733.html
Copyright © 2011-2022 走看看