We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 40833a2 commit 533dc1cCopy full SHA for 533dc1c
src/main/java/com/leetcode/arrays/MajorityElement.java
@@ -20,23 +20,19 @@ public class MajorityElement {
20
* @param nums
21
* @return
22
*/
23
- public static int majorityElement(int[] nums) {
24
- int count = 1;
25
- int majElem = nums[0];
+ public int majorityElement(int[] nums) {
+ int count = 0;
+ Integer candidate = null;
26
27
- for (int i = 1; i < nums.length; i++) {
28
- if (count <= 0) {
29
- majElem = nums[i];
30
- count = 0;
31
- }
32
- if (majElem == nums[i]) {
33
- count++;
34
- } else {
35
- count--;
+ for (int num : nums) {
+ if (count == 0) {
+ candidate = num;
36
}
+ count += (num == candidate) ? 1 : -1;
37
38
39
- return majElem;
+ return candidate;
+
40
41
42
public static void main(String[] args) {
0 commit comments