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;
         }
  • 相关阅读:
    POJ 1141 括号匹配 DP
    881. Boats to Save People
    870. Advantage Shuffle
    874. Walking Robot Simulation
    文件操作
    861. Score After Flipping Matrix
    860. Lemonade Change
    842. Split Array into Fibonacci Sequence
    765. Couples Holding Hands
    763. Partition Labels
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8426030.html
Copyright © 2011-2022 走看看