zoukankan      html  css  js  c++  java
  • leetcode- 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.

    题目含义:找到一个数组中,个数超过总个数一半的那个数!!!!

    注意:1、数组非空  2、这个数一定存在!!!!

    package leetcode;
    //这道题目是有约束的,该数组中一定存在这样的数,才能用Moore's Voting Algorithm!
    //否则找出的结果不正确!!
    //即要先判断是否存在,然后再找~
    //Moore's Voting Algorithm:http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html
    public class MajorityElement {
        public int majorityElement(int[] nums) {
            int count = 0;
            int majorityElement = nums[0];              //先令第一个数为这个marjor
            for (int x : nums) {
                if (x == majorityElement) {
                    ++count;
                } else {
                    --count;
                }
                if(count == 0){
                    majorityElement = x;
                    count = 1;
                }

            }
            return majorityElement;
            /* Arrays.sort(nums);                                //简单方法,但是排序,时间复杂度 nlogn ;可以做
                return nums[nums.length/2];*/
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub

        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    git 学习笔记 ---远程仓库
    git学习笔记 ---删除文件
    git 学习笔记 ---撤销修改
    git学习笔记 ---管理修改
    git学习笔记 ---工作区和暂存区
    git学习笔记 ---版本退回
    git 学习笔记 ---安装
    windows删除或修改本地Git保存的账号密码
    win10企业版永久激活方法
    IntelliJ IDEA 插件开发视频教程
  • 原文地址:https://www.cnblogs.com/neversayno/p/5395126.html
Copyright © 2011-2022 走看看