Leetcode 169&229(Java)

这是两道数组中找元素的题目,229是169的进阶版。先看169。

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

题目已经说明可以认为数组非空且出现次数大于数组元素个数一半的元素必定存在。想象一下,假设有n种不同颜色的小球,其中一种颜色的数量超过了总数的一半,那么我们把这些小球按颜色排序后,取最中间的小球,颜色一定是超过总数一半的那个颜色。所以这题可以排序,取中间值,AC码如下:

    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[(int)nums.length/2];
    }

229题目如下:
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.

这道题目中就没有任何的假设了,要判断数组为空等等特殊情况。一组数中要出现次数大于1/3的数字至多只能有两个,因此我们可以先遍历一遍数组,求出出现次数最多的两个元素,之后再次遍历数组,统计这两个数字出现的次数,最后判断是否大于数组长度的1/3。符合条件则加入result集,AC码如下:

    public List<Integer> majorityElement(int[] nums) {
        List<Integer> result = new ArrayList<Integer>();
        if(nums==null||nums.length==0)return result;
        int count1=0,count2=0,num1=nums[0],num2=nums[0];
        for(int i=0;i<nums.length;i++){
            if(nums[i]==num1){
                count1++;
            }else if(nums[i]==num2){
                count2++;
            }else if(count1==0){
                num1=nums[i];
                count1=1;
            }else if(count2==0){
                num2=nums[i];
                count2++;
            }else{
                count1--;
                count2--;
            }
        }

        count1=0;
        count2=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==num1){
                count1++;
            }else if(nums[i]==num2){
                count2++;
            }
        }
        if(nums.length/3<count1){
            result.add(num1);
        }
        if(nums.length/3<count2){
            result.add(num2);
        }


        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值