zoukankan      html  css  js  c++  java
  • 【Leetcode】169. Majority Element

    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.

    Tips:给定一个大小为n的数组,找到数组中出现次数大于n/2的数字。

    思路:解法一:将数组排序后,位于n/2位置的数字就是大于半数的数字。

    package easy;
    
    import java.util.Arrays;
    import java.util.Collections;
    
    public class L169MajorityElement {
        
         public int majorityElement(int[] nums) {
             int len=nums.length;
             int low=0;
             int high=len-1;
             int mid=low+(high-low)/2;
             Arrays.sort(nums);
             int bignum=nums[mid];
             return bignum;
                
            }
         public static void main(String[] args) {
            L169MajorityElement l169 = new L169MajorityElement();
            int[] nums={1,2,2,2,2,3};
            int bignum=l169.majorityElement(nums);
            System.out.println(bignum);
        }
    }

     解法二:按顺序遍历数组,第后一个数字等于前一个数字,count++.否则count--;

    当count=0时,就需要更换数字。

     public int majorityElement2(int[] nums) {
             int major=nums.length/2;
             int first=0;int count=1;
             for(int i=1;i<nums.length;i++){
                 if(nums[first]==nums[i]){
                     count++;
                 }else{
                     count--;
                 }
                 if(count==0){
                     first=i;
                     count=1;
                 }
             }
             int count2=0;
             for(int i=0;i<nums.length;i++){
                 if(nums[first]==nums[i]){
                     count2++;
                 }
                     
             }
             return count2>=major?nums[first]:0;
         }
  • 相关阅读:
    git clone SSL error解决
    day11_文件读写
    python练习day0120
    day12_文件读写_return
    GIS开发常用算法原理分析
    SoapToolkit3.0分发技术
    平台符合性审查测试工具安装教程
    MapX编程详解(C++)MapX发布技术
    Google地图定位偏移矫正
    串口通信编程多线程异步方式
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8426030.html
Copyright © 2011-2022 走看看