zoukankan      html  css  js  c++  java
  • LeetCode 169. Majority Element

    分析

    难度 易

    来源

    https://leetcode.com/problems/majority-element/

    JDK里的排序算法,效率就是高啊

    题目

    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.

    Example 1:

    Input: [3,2,3]
    Output: 3

    Example 2:

    Input: [2,2,1,1,1,2,2]
    Output: 2

    解答

     1 package LeetCode;
     2 
     3 import java.util.Arrays;
     4 import java.util.Stack;
     5 
     6 public class L169_MajorityElement {
     7     /*
     8     //34ms
     9     public int majorityElement(int[] nums) {
    10         Stack<Integer> stack=new Stack<Integer>();
    11         for(int i=0;i<nums.length;i++)
    12         {
    13             if(stack.isEmpty()||stack.peek()==nums[i])
    14                 stack.push(nums[i]);
    15             else
    16                 stack.pop();
    17         }
    18         return stack.peek();
    19     }*/
    20    /*
    21    //5ms
    22    public int majorityElement(int[] nums) {
    23         int count=0,result=0;
    24         for(int i=0;i<nums.length;i++)
    25         {
    26             if(count==0)
    27                 result=nums[i];
    28             if(result==nums[i])
    29                 count++;
    30             else
    31                 count--;
    32         }
    33         return result;
    34     }*/
    35    //3ms
    36     public int majorityElement(int[] nums) {
    37         Arrays.sort(nums);
    38         return nums[nums.length/2];
    39     }
    40     public static void main(String[] args){
    41         L169_MajorityElement l169=new L169_MajorityElement();
    42         //int[] nums={3,2,3};
    43         int[] nums={2,2,1,1,1,2,2};
    44         System.out.println(l169.majorityElement(nums));
    45     }
    46 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    UITableView学习笔记
    IOS基础之设置APP的名字、设置图标、添加等待加载时的图片
    UIScrollView,UIPageControl
    UIPickerView基本用法
    最大公约数和最小公倍数
    快速幂、快速乘
    素数筛
    最小生成树
    BZOJ1070 [SCOI2007]修车
    BZOJ1109 [POI2007]堆积木Klo
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9956535.html
Copyright © 2011-2022 走看看