# [LeetCode]--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.

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

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

public int majorityElement(int[] nums) {
if (nums.length == 0)
return 0;
int sum = 0;
int max = 0, temp = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++)
if (nums[i] == nums[j])
sum++;
if (sum > max) {
temp = i;
max = sum;
}
sum = 0;
}
return nums[temp];
}

public int majorityElement(int[] nums) {
if (nums.length == 0)
return 0;
int[] flag = new int[nums.length];
Arrays.fill(flag, 0);
for (int i = 0; i < nums.length - 1; i++) {
if (flag[i] != 0)
continue;
for (int j = i + 1; j < nums.length; j++) {
if (flag[j] != 0)
continue;
if (nums[i] != nums[j]) {
flag[i] = 1;
flag[j] = 1;
break;
}
}
}
for (int i = 0; i < flag.length; i++) {
if (flag[i] != 1) {
return nums[i];
}
}
return 0;
}

|
7月前
Leetcode 230. Kth Smallest Element in a BST

48 1
|
Python
LeetCode 378. Kth S Element in a Sorted Matrix

82 0
|

LeetCode 229. Majority Element II

63 0
|

LeetCode 162. Find Peak Element

80 0
|

LeetCode 169. 多数元素 Majority Element
LeetCode 169. 多数元素 Majority Element
74 0
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
90 0
LeetCode之Next Greater Element I
LeetCode之Next Greater Element I
64 0
|

LeetCode 229 Majority Element II（主要元素II）（Array）（Boyer–Moore majority vote algorithm）

1010 0
|

LeetCode 169 Majority Element（主要元素）（vector、map）

788 0
|
10天前
|

【数据结构与算法】：关于时间复杂度与空间复杂度的计算（C/C++篇）——含Leetcode刷题-2
【数据结构与算法】：关于时间复杂度与空间复杂度的计算（C/C++篇）——含Leetcode刷题
18 2