代码随想录day6 打卡

242

js dict 解法很好写

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    const charDict = {}
    if(s.length != t.length){
        return false
    }
    for(let i = 0 ; i < s.length; i++){
        if(s[i] in charDict){
            charDict[s[i]] = charDict[s[i]] + 1
        }else{
            charDict[s[i]] = 1
        }
    }

    for(let j = 0; j < t.length; j++){
        if(t[j] in charDict && charDict[t[j]] != 0){
            charDict[t[j]] = charDict[t[j]] - 1
        }else{
            return false
        }
    }

    return true
};

, 然后参考了sort 的解法,补充js sort 的解法

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isAnagram = function(s, t) {
    s = s.split('').sort().join('')
    t = t.split('').sort().join('')

    return s == t
};
class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());

        if(s == t)
            return true;
        else
            return false;
    }
};

349

不用哈希用了时间换空间的解法,includes

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
    const res = []
    const dict = {}
    for(let i = 0; i < nums1.length; i++){
        if(nums2.includes(nums1[i]) && !dict[nums1[i]]){
            dict[nums1[i]] = 1
            res.push(nums1[i])
        }
    }
    return res
};

202

来来回回卡 取余数折腾了老半天了,解法也很烂

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    const dict = {}
    while(true){
        let divide = 10
        let temp = n % divide
        let res = n - temp*divide/10
        let sum = 0
        while(res >= 0){
            sum = sum + temp * temp
            divide = divide * 10
            temp = (res % divide)/ (divide/10)
            res = res - temp*divide/10
        }
        if(sum == 1){
            return true
        }
        if(sum in dict){
            return false
        }
        n = sum
        dict[n] = 1
    }
};

用递归代替循环的解法可能更清楚一点

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    let dict = new Set()
    let temp = n;
    while(temp != 1){
        if(dict.has(temp)){
            console.log(temp)
            console.log(dict)
            return false
        }
        dict.add(temp)
        temp = getNext(temp)
    }
    return true
};

var getNext = function(n) {
    let totalSum = 0;
    while(n > 0){
        let d = n % 10;
        n = Math.floor(n / 10);
        totalSum += d*d;
    }
    return totalSum
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值