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
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];
}
}
⌊ 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];
}
}
相关文章推荐
- Spring+Log4j+ActiveMQ实现远程记录日志
- springmvc mongodb maven 整合
- 面向对象原则
- 常用查看Linux系统信息命令
- session入redis
- hdu5361(最短路+并查集)
- LoadRunner测试WebService的3种方式
- linux挂载windows文件夹
- 深度解决 SecurityException: User has not given permission to device UsbDevice
- jdk安装详解
- FSS指定磁盘布局进行vxvm的mirror-stripe(raid01)卷的制作
- Codeforces Round #361 (Div. 2) D Friends and Subsequences
- 如何解决mathpage.dll或MathType.dll文件找不到问题
- Codeforces Round #361 (Div. 2)E. Mike and Geometry Problem
- Leetcode Delete Node in a Linked List
- 集群管理脚本
- 外键约束
- 多线程面试必须掌握的
- systemctl 启动成功却提示没有权限(解决)
- LoadRunner如何在脚本运行时修改log设置选项