楼主: sicilianee
跳转到指定楼层
上一主题 下一主题
收起左侧

记录

🔗
 楼主| sicilianee 2017-8-23 13:11:46 | 只看该作者
全局:
本帖最后由 sicilianee 于 2017-8-23 14:59 编辑

0820 Sunday

2. Majority Element

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
    // key of an object cannot be a number, it will be converted to a string!!!
    const map = new Map();
    nums.forEach(num => {
        if (map.has(num)) {
            map.set(num, map.get(num) + 1);
        } else {
            map.set(num, 1);
        }
    });
    let maxPair = [0, 0];
    map.forEach((value, key) => {
        if (value >= maxPair[1]) {
            maxPair = [key, value];   
        }
    });
    return maxPair[0];
};
NOTE:
1. js object dict can only have string keys. If you use number as keys, it will be converted to string and when you retrieve it you will get a string not a number!


Better Solution:

/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
    // if set to 1, it still works for majority: why? because everyone needs to defeat the hero, but the hero
    // always needs to fight back and win one back. So other people will win at most one more element, but the hero
    // has one more element from the right begining, so he will always win the last battle and has the crown.
    // note: whoever wins the battle will win one element
    // However, set to 0 is the easist way.

    if (nums == null || nums.length === 0) {
        throw new Error('Illegal argument');
    }
    let majority = nums[0];
    let count = 0;
    nums.forEach(num => {
        if (count === 0) {
            majority = num;
            count = 1;
        } else {
            if (num === majority) {
                count++;
            } else {
                count--;
            }
        }
    });
    return majority;
};

回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-24 12:39:00 | 只看该作者
全局:
0823 Wednesday

1. Binary Tree Inorder Traversal

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
    const stack = [];
    const results = [];
    let node = root;
    while (node != null || stack.length > 0) {
        if (node != null) {
            stack.push(node);
            node = node.left;
        } else {
            node = stack.pop();
            results.push(node.val);
            node = node.right;
        }
    }
    return results;
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-25 13:21:01 | 只看该作者
全局:
0823 Wednesday

2.  4Sum II

/**
* @param {number[]} A
* @param {number[]} B
* @param {number[]} C
* @param {number[]} D
* @return {number}
*/
var fourSumCount = function(A, B, C, D) {
    const map1 = new Map();
    const map2 = new Map();
    buildMap(A, B, map1);
    buildMap(C, D, map2);
    let count = 0;
    map1.forEach((count1, sum1) => {
        if (map2.has(-sum1)) {
            count += count1 * map2.get(-sum1);
        }
    });
    return count;
   
   
    function buildMap(nums1, nums2, map) {
        nums1.forEach(num1 => {
            nums2.forEach(num2 => {
                const sum = num1 + num2;
                if (map.has(sum)) {
                    map.set(sum, map.get(sum) + 1);
                } else {
                    map.set(sum, 1);
                }
            });
        });
    }
};
When you don't know what to do, try hashmap.
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-25 13:36:59 | 只看该作者
全局:
本帖最后由 sicilianee 于 2017-8-25 13:44 编辑

0824 Thursday

1. First Unique Character in a String

/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
    const map = new Map();
    s.split('').forEach((c, index) => {
        if (map.has(c)) {
            map.set(c, -1)
        } else {
            map.set(c, index);
        }
    });
    let minIndex = Number.MAX_VALUE;
    map.forEach(index => {
        if (index >= 0) {
            minIndex = Math.min(index, minIndex);
        }
    });
    return minIndex === Number.MAX_VALUE ? -1 : minIndex;
};

Just set count to map.
Second loop loop the string, not the map. That is more straightforward.
Good way to convert min of array in js: spread operator.
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-27 00:23:55 | 只看该作者
全局:
0824 Thursday

2. Relative Ranks

/**
* @param {number[]} nums
* @return {string[]}
*/
var findRelativeRanks = function(nums) {
    // first make a copy and sort the array
    // second, for the copy, count and put each into map
    // loop the original and turn into result
    let copyNums = [...nums].sort((num1, num2) => num2 - num1);
    const map = new Map();
    copyNums.forEach((num, index) => {
        if (!map.has(num)) {
            map.set(num, index + 1);
        }
    });
    return nums.map(num => map.get(num)).map(rank => getRankString(rank));
   
   
    function getRankString (rank) {
        switch (rank) {
            case 1:
                return 'Gold Medal';
            case 2:
                return 'Silver Medal';
            case 3:
                return 'Bronze Medal';
            default:
                return `${rank}`;
        }
    }
                                    
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-28 03:17:32 | 只看该作者
全局:
0825 Friday

1. Shuffle an Array

It shows my solution was wrong. Don't know why.

/**
* @param {number[]} nums
*/
var Solution = function(nums) {
    this.nums = nums;
    const permutations = [];
    buildPermutations(nums, 0);
    this.permutations = permutations;
    console.log(permutations)
    let size = 1;
    for (let i = 1; i <= nums.length; i++) {
       size = size * i;
    }
    this.size = size;
    console.log(size);
   
   
    function buildPermutations (nums, i) {
        if (i === nums.length - 1) {
            permutations.push([...nums]);
        }
        for (let j = i; j < nums.length; j++) {
            ;[nums[i], nums[j]] = [nums[j], nums[i]];
            buildPermutations(nums, i + 1);
            ;[nums[i], nums[j]] = [nums[j], nums[i]];
        }
    }
};

/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function() {
    return this.nums;
};

/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function() {
    // 0 - N - 1
    const num = Math.floor(Math.random() * this.size);
    return this.permutations[num];
};

/**
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-30 12:09:19 | 只看该作者
全局:
本帖最后由 sicilianee 于 2017-8-30 13:13 编辑
sicilianee 发表于 2017-8-28 03:17
0825 Friday

1. Shuffle an Array

Another version:This shuffle is what underscore uses.
Passed when I submit again.

/**
* @param {number[]} nums
*/
var Solution = function(nums) {
    this.nums = nums;
};

/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function() {
    return this.nums;
};

/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function() {
    const numsCopy = [...this.nums];
    for (let i = 0; i < numsCopy.length; i++) {
        const random = Math.floor(Math.random() * (i + 1));
        ;[numsCopy, numsCopy[random]] = [numsCopy[random], numsCopy[i]];
    }
    return numsCopy;
};

/**
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
[/i]


回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-30 12:13:44 | 只看该作者
全局:
sicilianee 发表于 2017-8-28 03:17
0825 Friday

1. Shuffle an Array

Accepted using Fisher-Yates algorithm

/**
* @param {number[]} nums
*/
var Solution = function(nums) {
    this.nums = nums;
};

/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function() {
    return this.nums;
};

/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function() {
    const numsCopy = [...this.nums];
    for (let i = numsCopy.length - 1; i >= 0; i--) {
        const random = Math.floor(Math.random() * (i + 1));
        ;[numsCopy[i], numsCopy[random]] = [numsCopy[random], numsCopy[i]];
    }
    return numsCopy;
};

/**
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-30 15:48:50 | 只看该作者
全局:
0826 Saturday

1. Fraction Addition and Subtraction

/**
* @param {string} expression
* @return {string}
*/
var fractionAddition = function(expression) {
    if (!expression) {
        return '';
    }
    expression = expression[0] === '-' ? expression : `+${expression}`;
    const signs = expression.split('').filter(c => ['+', '-'].includes(c)).map(str => {
        return str === '+' ? 1 : -1;
    });
    const nums = expression.split(/\+|-/).filter(num => num); // not includeing first
    console.log(nums);
    const items = nums.map(num => num.split('\/').map(part => Number.parseInt(part, 10)))
        .map(([num, den], index) => ({num: signs[index] * num, den}));
    console.log(items);
    const item = items.reduce((sum, item) => {
        let den = sum.den * item.den;
        let num = sum.num * item.den + item.num * sum.den;
        console.log(den);
        console.log(num);
        // zero and neg
        if (num === 0) {
            den = 1;
        } else {
            const aGcd = gcd(Math.abs(num), den);
            num = num / aGcd;
            den = den / aGcd;            
        }
        return {num, den};
    });
    return item < 0
        ? `-${item.num}/${item.den}`
        : `${item.num}/${item.den}`;

};
// positive
function gcd (a, b) {
    let bigger, smaller;
    console.log(a);
    console.log(b);
    if (a >= b) {
        bigger = a;
        smaller =b;
    } else {
        bigger = b;
        smaller = a;
    }
    if (bigger % smaller === 0) {
        return smaller;
    } else {
        return gcd(smaller, bigger % smaller);
    }
}
TODO: revisit


补充内容 (2017-8-31 12:05):
The return part is wrong. But it returns the correct answer because item < 0 is never truthy
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-8-31 12:03:12 | 只看该作者
全局:
sicilianee 发表于 2017-8-30 15:48
0826 Saturday

1. Fraction Addition and Subtraction

/**
* @param {string} expression
* @return {string}
*/
var fractionAddition = function(expression) {
    if (expression == null || expression.length === 0) {return '';}
    expression = expression[0] === '-' ? expression : `+${expression}`;
    const signs = expression.split('').filter(c => ['+', '-'].includes(c)).map(sign => {
        return sign === '+' ? 1 : -1;
    });
    const items = expression.split(/\+|-/).filter(str => str).map(str => str.split('/')
        .map(numStr => Number.parseInt(numStr, 10)))
        .map(([num, den], index) => ({num: num * signs[index], den}));
    const sum = items.reduce((sum, item) => {
        let den = sum.den * item.den;
        let num = sum.num * item.den + item.num * sum.den;
        const aGcd = gcd(Math.abs(num), den);
        den = den / aGcd;
        num = num / aGcd;
        return {num, den};
    });
    return `${sum.num}/${sum.den}`;
};

function gcd (a, b) { // non-neg
    while (b !== 0) {
        ;[a, b] = [b, a % b];
    }
    return a;
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表