1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109<= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
题意
在一个数组中找两个数的和等于目标值
思路
两重循坏遍历数组
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++)
if(nums[i] + nums[j] == target)
return {i, j};
};
return {};
};
};
49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
题意
在一个字符串数组中,把由相同字符组成的字符串放在一个数组中。
思路
遍历字符串数组,然后将每个字符串进行排序,把排序相同的元素放进哈希表中(key存排序后的字符串,值用一个字符数组存对应的字符),最后把哈希表的值取出来放进vector中输出
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hash;
for(auto x : strs){
string y = x;
sort(y.begin(), y.end());
hash[y].push_back(x);
}
vector<vector<string>> res;//存的值也是vector的形式
for(auto item : hash){
res.push_back(item.second);
}
return res;
}
};
128. 最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
题意
一个整数数组中,找到数字连续的最长序列的长度(不要求序列元素在原数组中连续)。
思路
把数组中的数字都先放进unordered_set中,找到其中数字是连续最小的数(count(x)存在,count(x-1)不存在),然后把这个数移出,最后循环找出数字连续的最大的数y,res = y - x + 1;
代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s;
for(auto x : nums) s.insert(x);
int res = 0;
for(auto x : nums){
if(s.count(x) && !s.count(x-1)){
int y = x;
s.erase(y);
while(s.count(y+1)){
y++;
s.erase(y);
}
res = max(res, y - x + 1);
}
}
return res;
}
};
283. 移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
题意
把数组中的零都移动到数字的最后,其他数的位置保持不变
思路
遍历数组,把不是零的数放进原数组(用另一个指针j),然后把数值其他位置都补零。
代码
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] != 0){
nums[j++] = nums[i];
}
}
for(int i = j; i < nums.size(); i++){
nums[i] = 0;
}
}
};