📣 VIP通行证夏日特惠 限时立减$68
楼主: sicilianee
跳转到指定楼层
上一主题 下一主题
收起左侧

记录

🔗
 楼主| sicilianee 2017-11-13 07:41:56 | 只看该作者
全局:
1112 8. K-diff Pairs in an Array

/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findPairs = function(nums, k) {
    // todo: check
    const map = new Map();
    for (let num of nums) {
        const count = map.has(num) ? map.get(num) + 1 : 1;
        map.set(num, count);
    }
    let res = 0;
    for (let [num, count] of map.entries()) {
        if (k === 0 && count > 1) {
            res++;
        }
        if (k > 0 && map.get(num + k) > 0) { // 我们加上k而不是用绝对值,这样就不必担心重复了
            res++;
        }
    }
    return res;
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 07:55:51 | 只看该作者
全局:
1112 9. Sqrt(x)

/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
    let left = 0;
    let right = x;
    while (left <= right) { // !!!! can equal
        // take right in the end
        const mid = left + Math.floor((right - left) / 2);
        const val = mid * mid;
        console.log(mid, val)
        if (val === x) {
            return mid; // !!! not return the val!
        } else if (x < val) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
        // !!!! what the heck is this? don't do the update blindly ??? Just check loop vars each time you exit a loop
        // left++;
        // right--;
    }
    return right;
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 07:56:23 | 只看该作者
全局:

Maybe we can automate it? like programming or driving?
check
1. loop, vars
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 08:09:05 | 只看该作者
全局:
1112 10.  Third Maximum Number

/**
* @param {number[]} nums
* @return {number}
*/
var thirdMax = function(nums) {
    // check
    if (nums.length < 3) {
        return Math.max(...nums);
    }
    let first = -Infinity;
    let second = -Infinity;
    let third = -Infinity;
    for (let num of nums) {
        if (num > first) {
            third = second;
            second = first;
            first = num;
        } else if (num > second && num < first) { // !!! because we have equal, must check < here
            third = second;
            second = num;
        } else if (num > third && num < second) {
            third = num;
        }
    }
    // !!! f, s, t they could all equal !!!!
    return third !== -Infinity ? third : first;
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 09:45:45 | 只看该作者
全局:
1112 11. Number of Atoms

/**
* @param {string} formula
* @return {string}
*/
var countOfAtoms = function(formula) {
    // 这种傻逼题目最大的阻碍是怎么样先把有效的输入元素parse出来。然后才能写算法
    // valid els: H, (), 2
    // H3O6H
    // H3(O6H)4
    // K4(ON(SO3)2)2
   
    // check
    if (formula == null) {throw new Error()}
    if (formula.length === 0) {return 0}
    const list = [];
    let i = 0;
    while (i < formula.length) {
        if (formula[i] >= 'A' && formula[i] <= 'Z') {
            let j = i + 1;
            while (j < formula.length && formula[j] >= 'a' && formula[j] <= 'z') {
                j++;
            }
            const str = formula.slice(i, j);
            list.push(str);
            i = j;
        } else if (formula[i] === '(' || formula[i] === ')') {
            list.push(formula[i]);
            i++;
        } else {
            let j = i;
            while (j < formula.length && formula[j] >= '0' && formula[j] <= '9') {
                j++;
            }
            const str = formula.slice(i, j);
            list.push(Number.parseInt(str, 10));
            i = j;
        }
    }
    // algorithm starts
    const stack = [{}];
    let dict = stack[stack.length - 1];
    for (let [i, el] of list.entries()) {
        // (), number, str
        if (Number.isInteger(el)) {
            // do nothing
        } else if (el === '(') {
            dict = {};
            stack.push(dict);
        } else if (el === ')') {
            let count = (i + 1 === list.length || !Number.isInteger(list[i + 1])) ? 1 : list[i + 1];
            stack.pop();
            const topDict = stack[stack.length - 1];
            for (let [key, val] of Object.entries(dict)) {
                val = val * count;
                topDict[key] = (topDict[key] || 0) + val; // !!!! add value, not count !!! shit. One variable ruins all
            }
            dict = topDict;
        } else {
            dict[el] = dict[el] || 0;
            let count = (i + 1 === list.length || !Number.isInteger(list[i + 1])) ? 1 : list[i + 1];
            dict[el] = dict[el] + count;
        }
        i++;
    }
    // should have only one dict left in the stack
    const keys = Object.keys(dict).sort();
    return keys.map(key => dict[key] === 1 ? key : `${key}${dict[key]}`).join('');
   
};


这种傻逼题目之所以傻逼,
第一是你要parse输入到你可以操作的element
第二是代码太长,有一个变量搞错了,整个都错了。而且关键是这种i用成j ,val用成count,太难发现。错了就gg了。

第一点我们可以先过一遍,第二点怎么避免呢?
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 09:47:53 | 只看该作者
全局:
sicilianee 发表于 2017-11-13 09:45
1112 11. Number of Atoms

/**

第一点我们也可以建立class数据结构来装operands
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 13:21:08 | 只看该作者
全局:
1112 12. Serialize and Deserialize Binary Tree

bfs比pre order 难很多呀

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/

/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function(root) {
    if (root == null) {return '#'}
    const list = [];
    const q = [root];
    while (q.length > 0) {
        const size = q.length;
        const level = [];
        for (let i = 0; i < size; i++) {
            const node = q.shift();
            const val = node == null ? '#' : node.val;
            list.push(val);
            if (node != null) {
                level.push(node.left);
                level.push(node.right);
            }
        }
        const has = level.some(node => node != null);
        if (has) {
            q.push(...level);
        }
    }
    console.log(list.join(','))
    return list.join(',')
};

/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function(data) {
    const list = data.split(',').filter(str => str);
    if (list.length === 0 || list[0] === '#') {return null}
    const root = new TreeNode(Number.parseInt(list[0], 10));
    const q = [root];
    let i = 1;
    while (q.length > 0) {
        const node = q.shift();
        if (node != null && i < list.length) {
            const leftVal = list[i];
            const rightVal = list[i + 1];
            // console.log(leftVal, rightVal)
            i = i + 2;
            if (leftVal == '#') {
                node.left = null;
            } else {
                node.left = new TreeNode(Number.parseInt(leftVal, 10)); // !!!!! create a new node and assign, not just the number value !!!!
                q.push(node.left);
            }
            if (rightVal == '#') {
                node.right = null;
            } else {
                node.right = new TreeNode(Number.parseInt(rightVal, 10));
                q.push(node.right);
            }
            // console.log('the node')
            // console.log(node)
        }
    }
    console.log(root)
    return root;
};

/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-13 13:21:52 | 只看该作者
全局:
sicilianee 发表于 2017-11-13 13:21
1112 12. Serialize and Deserialize Binary Tree

bfs比pre order 难很多呀

需要再多想想这道题
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-14 11:38:14 | 只看该作者
全局:
1113 1. Count Primes

/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
    if (n < 2) {return 0;}
    const arr = Array(n).fill(true);
    const limit = Math.floor(Math.sqrt(n));
    for (let i = 2; i <= limit; i++) { // !!! why can equal? because we use floor.
        if (arr[i]) {
            for (let j = i * i; j < n; j = j + i) {
                arr[j] = false;
            }
        }
    }
    let count = 0;
    for (let i = 2; i < n; i++) {
        if (arr[i]) {count++;}
    }
    return count;
};
回复

使用道具 举报

🔗
 楼主| sicilianee 2017-11-14 12:00:02 | 只看该作者
全局:
1113 2. Excel Sheet Column Title

/**
* @param {number} n
* @return {string}
*/
var convertToTitle = function(n) {
    let str = '';
    while (n != 0) {
        n = n - 1;
        const current = n % 26;
        const c = String.fromCharCode('A'.charCodeAt(0) + current);
        str = c + str; // !!!! newly added put in front
        n = Math.floor(n / 26);
    }
    return str
};
回复

使用道具 举报

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

本版积分规则

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