LeetCode__169. Majority Element

来源:互联网 发布:商贸公司取名软件 编辑:程序博客网 时间:2024/05/04 18:03

169. 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.

如题,给定一个数组,找出其中元素个数超过一半的数,

本来写不好,但是后面有一个假设,及这样的数数组中一定存在,这样难度就大大降低了。

借鉴了上一个程序:

public class Solution {    public int majorityElement(int[] nums) {       if(nums.length==1) return nums[0];        Arrays.sort(nums);        int sum = 1;        for(int i = 0; i <nums.length-1; i++){            if(nums[i]==nums[i+1]){               sum++;            }else{                sum = 1;            }            if(sum>nums.length/2){                return nums[i];            }        }        return nums[0];//这个我不想加,但是必须要返回值,所以……    }}

很简单了……

1 0
原创粉丝点击