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的编辑器高大上啊
  • 相关阅读:
    webpack初识
    Vue+ElementUi项目实现表格-单行拖拽
    promise/async与await 的执行顺序梳理
    MDN社区
    angularjs中的异步操作
    javascript中的字符串和数组的互转
    angularjs的练习题
    angularjs基础知识
    开发的两种方式
    ASP.NET中的HttpClient发送请求
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9956535.html
Copyright © 2011-2022 走看看