LeetCode--多数元素(数组排序、Map特性、位运算、摩尔投票)

在这里插入图片描述

题目分析

原题:

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

进阶:
尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

示例 1:

输入:[3,2,3]
输出:3
示例 2:

示例 2:

输入:[2,2,1,1,1,2,2]
输出:2

解题思路

  • 数据结构与算法: 数组、Map特性、位运算、摩尔投票
  • 实现思路1: 利用数组排序,取中间元素;
  • 实现思路2: 利用Map特性,元素作为key,元素个数作为value;
  • 实现思路3: 利用位运算,int整型32位空间,如果所有元素在某一个位置都是1,那目标元素该位置肯定也是1;
  • 实现思路4: 利用摩尔投票,数字一样的表示一个团体,内部混战,元素相同+1,不同-1;

代码实现

具体代码:

/**
 * 多数元素(数组排序、Map特性、位运算、摩尔投票)
 **/
public class MajorityElement {
    
    
    public static void main(String[] args) {
    
    
        int[] nums = {
    
    3,2,3};
        //int[] nums = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(nums));
    }

    public static int majorityElement(int[] nums){
    
    
        //思路1:数组排序
//        Arrays.sort(nums);
//        return nums[nums.length/2];

        //思路2:Map特性
//        Map<Integer,Integer> map = new HashMap<>();
//        int length = nums.length;
//        for(int i=0;i<length;i++){
    
    
//            int count = 0;
//            count = map.getOrDefault(nums[i],0) + 1;
//            if(count > length/2){
    
    
//                return nums[i];
//            }
//            map.put(nums[i],count);
//        }
//        return -1;

        //思路3:位运算
//        int major=0;
//        int length = nums.length;
//        for(int i=0,mark = 1;i<32;i++,mark <<= 1){
    
    
//            int curBinCounts = 0;
//            for (int j=0;j<length;j++){
    
    
//                if ((nums[j] & mark) == mark){
    
    
//                    curBinCounts++;
//                }
//                if (curBinCounts > length /2){
    
    
//                    major |= mark;
//                    break;
//                }
//            }
//        }
//        return major;

        //思路4:摩尔投票法
        int result = nums[0];
        int count = 1;
        int length = nums.length;
        for(int i=1;i<length;i++){
    
    
            if(count == 0){
    
    
                count ++;
                result = nums[i];
            }else if (nums[i] == result){
    
    
                count++;
            }else {
    
    
                count --;
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/JustinQin/article/details/120830383