Skip to content

Commit 6ba659c

Browse files
committed
finish 169
1 parent 65f5602 commit 6ba659c

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

101-200/169. Majority Element.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# 169. Majority Element
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Array, Divide and Conquer, Bit Manipulation.
5+
- Similar Questions: Majority Element II.
6+
7+
## Problem
8+
9+
Given an array of size *n*, find the majority element. The majority element is the element that appears **more than** ```⌊ n/2 ⌋``` times.
10+
11+
You may assume that the array is non-empty and the majority element always exist in the array.
12+
13+
**Example 1:**
14+
15+
```
16+
Input: [3,2,3]
17+
Output: 3
18+
```
19+
20+
**Example 2:**
21+
22+
```
23+
Input: [2,2,1,1,1,2,2]
24+
Output: 2
25+
```
26+
27+
## Solution 1
28+
29+
```javascript
30+
/**
31+
* @param {number[]} nums
32+
* @return {number}
33+
*/
34+
var majorityElement = function(nums) {
35+
var map = {};
36+
var max = 0;
37+
var majorNum = 0;
38+
var len = nums.length;
39+
for (var i = 0; i < len; i++) {
40+
if (!map[nums[i]]) map[nums[i]] = 0;
41+
map[nums[i]]++;
42+
if (map[nums[i]] > max) {
43+
majorNum = nums[i];
44+
max = map[nums[i]];
45+
}
46+
}
47+
return majorNum;
48+
};
49+
```
50+
51+
**Explain:**
52+
53+
nope.
54+
55+
**Complexity:**
56+
57+
* Time complexity : O(n).
58+
* Space complexity : O(n).
59+
60+
## Solution 2
61+
62+
```javascript
63+
/**
64+
* @param {number[]} nums
65+
* @return {number}
66+
*/
67+
var majorityElement = function(nums) {
68+
var count = 0;
69+
var majorNum = 0;
70+
var len = nums.length;
71+
for (var i = 0; i < len; i++) {
72+
if (!count) {
73+
majorNum = nums[i];
74+
count = 1;
75+
} else {
76+
count += (nums[i] === majorNum ? 1 : -1);
77+
}
78+
}
79+
return majorNum;
80+
};
81+
```
82+
83+
**Explain:**
84+
85+
nope.
86+
87+
**Complexity:**
88+
89+
* Time complexity : O(n).
90+
* Space complexity : O(1).

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy