-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathSolution.java
89 lines (65 loc) · 1.92 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package LeetCode.Easy.MajorityElement;
// import java.util.HashMap;
/*
169. Majority Element
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
n == nums.length
1 <= n <= 5 * 104
-231 <= nums[i] <= 231 - 1
Follow-up: Could you solve the problem in linear time and in O(1) space?
*/
public class Solution {
public int majorityElement(int[] nums) {
/**
* * Hashmap approach
* * TC: O(n), SC: O(n)
*/
// HashMap<Integer, Integer> map = new HashMap<>();
// for (int num : nums) {
// map.put(num, map.getOrDefault(num, 0) + 1);
// if (map.get(num) > (nums.length / 2))
// return num;
// }
/**
* * Moore's Voting Algorithm
* * TC: O(n), SC: O(1)
*/
int majorityIndex = 0, count = 1;
for (int i = 1; i < nums.length; i++)
// If the element at majorityIndex
// is equal to the current element
// increment the count
if (nums[majorityIndex] == nums[i]) ++count;
else {
// Otherwise, decrement the
// count
--count;
// If the count reaches 0,
// then set the majorityIndex
// to the current index and
// reset the count value to 1
if (count == 0) {
majorityIndex = i;
count = 1;
}
}
// Finally, return the
// majority element
return nums[majorityIndex];
}
public static void main(String[] args) {
Solution solution = new Solution();
// should be 3
System.out.println(solution.majorityElement(new int[] {3, 2, 3}));
// should be 2
System.out.println(solution.majorityElement(new int[] {2, 2, 1, 1, 1, 2, 2}));
}
}