49. Group Anagrams
- Total Accepted: 109658
- Total Submissions: 344938
- Difficulty: Medium
- Contributors: Admin
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
Subscribe to see which companies asked this question
/**
* @param {string[]} strs
* @return {string[][]}
*/
var griddle = [];
var result = [];
var groupAnagrams = function(strs)
{ griddle = new Map();
result = [];
for(var str in strs)
{
var key = Array.from(strs[str]).sort().join();
if (griddle.has(key))
{ griddle.get(key).push(strs[str]) }
else
{
griddle.set(key, [strs[str]]);
}
}
griddle.forEach((e, i , m)=>{ result.push(e) });
return result;
}
// var groupAnagrams = function(strs) { //n 的立方,所以还是换实现吧
// griddle = [];
// result = [];
// for (var str in strs)
// {
// if (mappedInGriddle(strs[str]) === false)
// {
// makeNewGriddle(strs[str])
// }
// }
// return result;
// };
var mappedInGriddle = function(str)
{
for (var count = 0 ; count < griddle.length ; count++)
{
var eachCopy = griddle[count].concat();
for(var x = 0 ; x < str.length ; x++)
{
eachCopy[ str.charCodeAt(x) - "a".charCodeAt(0)] --;
}
if (eachCopy.every(testAllZero)) {result[count].push(str); return true; }
}
return false;
};
var testAllZero = function(element ,index , array)
{
return element === 0;
};
var makeNewGriddle = function(str)
{
var array = new Array(26);
array.fill(0);
for( var x = 0 ; x < str.length ; x++)
{
array[ str.charCodeAt(x) - "a".charCodeAt(0) ]++;
}
// console.log("str:"+str+" array:"+ array )
griddle.push(array);
result.push([str]);
};
两种方案,使用的内存空间是一样的。 一种时间复杂度是 n*n* strLength, 一种是 n * strLength * log( strLength), 系统拒绝了前面一种。。。
这道题主要是对Array.from 和 Map的get,has,set的使用吧。
以及对时间复杂度的选择,虽然辛苦做了第一种实现然而是无用的。