字母异位词分组(Leecode49)&最大子序和(Leecode53)
49. 字母异位词分组
题目
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:[ [“ate”,“eat”,“tea”], [“nat”,“tan”], [“bat”]]
说明:所有输入均为小写字母, 不考虑答案输出的顺序。
思路
1.检查是否为空数组
2建立一个长度为 26 26 26的数组,起始值为 03 03 03遍历所有字符串,将字母的出现频率放到数组的对应位置里(利用 a s c i asci asci码)
4·遍历数组,按照相同字母出现频率进行分组 B k Bk Bk( p p p用 h a s h M a p hashMap hashMap).
5.遍历 m a p map map,将结果返回
javascript。
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
if(strs.length===0){
return [];
}
const map = new Map();
for(const str of strs){
const characters =Array(26).fill(0);//填入数组长度,全部填充为0
for(let i=0;i<str.length;i++){
const ascii =str.charCodeAt(i)-97;//字母排到相应文职
characters[ascii]++;
}
const key =characters.join("");//现在是个数组,将其转换成字符串
if(map.has(key)){
map.set(key,[...map.get(key),str])
}else{
map.set(key,[str])
}
}
const result =[];
for(const arr of map){
result.push(arr[1]);
}
return result;
};
53. 最大子序和
题目
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
思路
假设 n u m s nums nums数组的长度是 n n n,下标从 0 0 0到 n − 1 n−1 n−1。
我们用 a i a_i ai 代表 n u m s [ i ] nums[i] nums[i],用 f ( i ) f(i) f(i)代表以第 i i i个数结尾的「连续子数组的最大和」,那么很显然我们要求的答案就是:
max 0 ≤ i ≤ n − 1 { f ( i ) } \max_{0 \leq i \leq n - 1} \{ f(i) \} 0≤i≤n−1max{f(i)}
因此我们只需要求出每个位置的 f ( i ) f(i) f(i),然后返回 f f f数组中的最大值即可。那么我们如何求 f ( i ) f(i) f(i) 呢?我们可以考虑 a i a_i ai单独成为一段还是加入 f ( i − 1 ) f(i−1) f(i−1) 对应的那一段,这取决于 a i a_i ai和 f ( i − 1 ) + a i f(i−1)+a_i f(i−1)+ai的大小,我们希望获得一个比较大的,于是可以写出这样的动态规划转移方程:
f ( i ) = max { f ( i − 1 ) + a i , a i } f(i) = \max \{ f(i - 1) + a_i, a_i \} f(i)=max{f(i−1)+ai,ai}
for (const auto &x: nums)//const auto &x: nums访问nums,x为不断后移至的数
C++
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int pre = 0, maxAns = nums[0];
for (const auto &x: nums) {//const auto &x: nums访问nums,x为不断后移至的数
pre = max(pre + x, x);
maxAns = max(maxAns, pre);
}
return maxAns;
}
};