您的位置:首页 > 其它

Leetcode Majority Element

2016-07-07 21:15 363 查看
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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

Difficulty: Easy

Solution 1: Bit Manipulation

public class Solution {
public int majorityElement(int[] nums) {
int ans = 0;
for(int i = 0; i < 32; i++){
int count = 0;
for(int j = 0; j < nums.length; j++){
if(((nums[j] >> i) & 1) == 1){
count++;
}
}
if(count > nums.length/2){
ans = ans | (1 << i);
}
}
return ans;
}
}

Solution 2: 
public class Solution {
public int majorityElement(int[] nums) {
int count = 0, ans = 0;
for(int i = 0; i < nums.length; i++){
if(count == 0){
ans = nums[i];
count++;
}
else if(ans == nums[i]){
count++;
}
else{
count--;
}
}
return ans;
}
}

Solution 3 : Sort
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: