• 【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;
         }
  • 相关阅读:
    sql server 数据查询基础
    sqlserver 用SQL语句操作数据
    sql server 用表组织数据
    sql server 程序的集散地 数据库
    JAVA 面向对象 File I/O
    JAVA 面向对象 多线程
    JAVA 面向对象 集合框架
    JAVA 面向对象 异常
    js内置对象、定时函数、document对象
    DOM
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8426030.html
Copyright © 2020-2023  润新知