find the majority of the elements

Given an array of size n, find the majority of elements in it: elements that occur more than n/2

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ArrayHomeWork {
    
    
    /*给定一个大小为n的数组,找到其中的多数元素:出现次数大于n/2的元素
    * 哈希表方法,映射存储出现元素以及该元素出现的次数*/
    public int manyNum(int[] num){
    
    
        //JDK的哈希表用法
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        //遍历数组的过程中将不再重复的元素及其出现的次数存储到应设中
        for (int i = 0; i < num.length; i++) {
    
    
            //若此时映射中存在元素
            if (hashMap.containsKey(num[i])){
    
    //判断此时数据集中是否包含元素key -> num[i]
                //此时只需要将出现次数+1
                int value = hashMap.get(num[i]);//从映射中取出该key值对应的value值
                hashMap.put(num[i],value + 1);
            }else{
    
    
            //若此时映射中还没有元素
            //哈希表的存储方法 hashMap.put(不重复的元素,value)
            hashMap.put(num[i],1);//向映射中存储一对元素
        }
    }
        //在数据集中找到出现次数 》 n/2 的元素
        //哈希表遍历
        Set<Map.Entry<Integer,Integer>> set = hashMap.entrySet();
        for (Map.Entry<Integer,Integer> entry : set){
    
    
            //取出每个元素出现的次数-value值
            if (entry.getValue() > num.length / 2){
    
    
                return entry.getKey();
            }
        }
        return -1;

        }
    public static void main(String[] args) {
    
    
        ArrayHomeWork homeWork = new ArrayHomeWork();
        int[] num1 = {
    
    2 , 2 , 4 , 2};
        int[] num2 = {
    
    5 , 7 , 9 , 1};
        System.out.println(homeWork.manyNum(num1));
        System.out.println(homeWork.manyNum(num2));
    }
}

// Determine whether there are three consecutive elements in the array that are odd numbers //

 public boolean consecutiveOdds(int[] num){
    
    
        int count = 0;//记录当前数组中出现连续奇数的个数
        for (int i : num){
    
    //for-each数组:不修改原数组
            if (i % 2 != 0 ){
    
    
                count++;
            }else{
    
    
                count = 0;//i是偶数,重置count变量
            }
            if (count == 3){
    
    
                return true;
            }
        }
        return false;
    }*/

    /*public static void main(String[] args) {
        ArrayHomeWork homeWUork = new ArrayHomeWork();
        int[] num1 = {2 , 6 , 4 , 1};
        int[] num2 = {5 , 7 , 9 , 1};
        System.out.println(homeWork.consecutiveOdds(num1));
        System.out.println(homeWork.consecutiveOdds(num2));
    }
}

Guess you like

Origin blog.csdn.net/biteqq/article/details/123336797