File tree Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change 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).
You can’t perform that action at this time.
0 commit comments