-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169.MajorityElement.cs
50 lines (46 loc) · 1.64 KB
/
169.MajorityElement.cs
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
//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.
//Moor's Voting Algorithm
//Time Complexity: O(n)
//Space Complexity: O(1)
public class Solution {
public int MajorityElement(int[] nums) {
int count = 1;
int candidate = nums[0];
//Find the candidate for majority element using Moore's Voting Algorithm
for(int i = 1; i < nums.Length; i++){
//If the current element is the same as the candidate, then increment the count
if(nums[i] == candidate)
count++;
else{
//If the current element is different from the candidate, then decrement the count
count--;
if(count == 0){
//If the count is 0, then the current element is the candidate for majority element
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}
}
//HashMap
//Time Complexity: O(n)
//Space Complexity: O(n)
public class Solution {
public int MajorityElement(int[] nums) {
Dictionary<int,int> Counter = new();
//Count the frequency of each element
for(int i = 0; i < nums.Length; i++){
if(Counter.ContainsKey(nums[i]))
Counter[nums[i]]++;
else
Counter[nums[i]] = 1;
}
//Return the element with the maximum frequency
return Counter.MaxBy(x => x.Value).Key;
}
}