Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 533dc1c

Browse files
Using ternary operator
1 parent 40833a2 commit 533dc1c

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/main/java/com/leetcode/arrays/MajorityElement.java

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,19 @@ public class MajorityElement {
2020
* @param nums
2121
* @return
2222
*/
23-
public static int majorityElement(int[] nums) {
24-
int count = 1;
25-
int majElem = nums[0];
23+
public int majorityElement(int[] nums) {
24+
int count = 0;
25+
Integer candidate = null;
2626

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--;
27+
for (int num : nums) {
28+
if (count == 0) {
29+
candidate = num;
3630
}
31+
count += (num == candidate) ? 1 : -1;
3732
}
3833

39-
return majElem;
34+
return candidate;
35+
4036
}
4137

4238
public static void main(String[] args) {

0 commit comments

Comments
 (0)