Skip to main content

3 posts tagged with "counting"

View All Tags

· One min read

https://leetcode.com/problems/ransom-note/

Solution 1

/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function (ransomNote, magazine) {
const splitB = magazine.split('');

for (let i = 0; i < ransomNote.length; i++) {
const matchedIndex = splitB.indexOf(ransomNote[i]);
if (matchedIndex !== -1) {
splitB.splice(matchedIndex, 1);
} else {
return false;
}
}

return true;
};

Runtime: 116 ms, faster than 76.45% of JavaScript online submissions for Ransom Note.

Memory Usage: 46.5 MB, less than 30.65% of JavaScript online submissions for Ransom Note.

· One min read

https://leetcode.com/problems/majority-element/

Solution 1

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
const element = {};

for (const num of nums) {
if (element[num]) {
element[num]++;
} else {
element[num] = 1;
}
}

let max = 0;
let targetNum = '';

for (let e in element) {
if (element[e] > max) {
max = element[e];
targetNum = e;
}
}

return Number(targetNum);
};

· One min read

https://leetcode.com/problems/first-unique-character-in-a-string/

Solution 1

/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function (s) {
const hashMap = {};
for (let i = 0; i < s.length; i++) {
if (hashMap[s[i]]) {
hashMap[s[i]] = {
...hashMap[s[i]],
count: hashMap[s[i]].count + 1,
};
} else {
hashMap[s[i]] = {
index: i,
count: 1,
};
}
}

const filteredResult = Object.entries(hashMap)
.map(([key, value]) => {
if (value.count === 1) {
return value.index;
}
})
.filter((value) => value !== false && value !== undefined);

return filteredResult.length === 0 ? -1 : filteredResult[0];
};