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 }

 

 

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

转载于:https://www.cnblogs.com/flowingfog/p/9956535.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值