Skip to content

Commit c32a8fe

Browse files
committed
add 4 new drafts
1 parent dbb04e1 commit c32a8fe

File tree

4 files changed

+87
-0
lines changed

4 files changed

+87
-0
lines changed

101-200/169-majority-element.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
// sort and find middle
3+
var majorityElement = function (nums) {
4+
nums.sort((a, b) => a - b);
5+
6+
const l = nums.length;
7+
8+
if (l % 2 === 0) {
9+
return nums[l / 2]
10+
} else {
11+
return nums[(l - 1) / 2]
12+
}
13+
};
14+
15+
// Boyer–Moore majority vote algorithm
16+
// https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
17+
var majorityElement = function (nums) {
18+
let maj = 0, count = 1;
19+
20+
for (let i = 1; i < nums.length; i++) {
21+
if (nums[i] === nums[maj]) {
22+
count++
23+
} else {
24+
count--;
25+
}
26+
27+
if (count === 0) {
28+
maj = i;
29+
count = 1;
30+
}
31+
}
32+
return nums[maj]
33+
};
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
3+
var oddCells = function (n, m, indices) {
4+
const row = new Array(n).fill(0)
5+
const col = new Array(m).fill(0)
6+
7+
for (let i = 0; i < indices.length; i++) {
8+
row[indices[i][0]]++;
9+
col[indices[i][1]]++;
10+
}
11+
12+
let count = 0;
13+
14+
for (let i = 0; i < n; i++) {
15+
for (let j = 0; j < m; j++) {
16+
if ((row[i] + col[j]) % 2 !== 0) {
17+
count++;
18+
}
19+
}
20+
}
21+
22+
return count;
23+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
3+
var subtractProductAndSum = function (n) {
4+
let product = 1, sum = 0;
5+
6+
while (n > 0) {
7+
const digit = n % 10;
8+
n = parseInt(n / 10);
9+
10+
product = product * digit;
11+
sum += digit
12+
}
13+
14+
return product - sum
15+
};

801-900/867-transpose-matrix.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
3+
var transpose = function (A) {
4+
5+
const result = [];
6+
7+
for (let i = 0; i < A[0].length; i++) {
8+
const col = []
9+
for (let j = 0; j < A.length; j++) {
10+
col.push(A[j][i]);
11+
}
12+
result.push(col)
13+
}
14+
15+
return result
16+
};

0 commit comments

Comments
 (0)