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
}