flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

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 }

 

 

posted on 2018-11-14 10:19  flowingfog  阅读(100)  评论(0编辑  收藏  举报