【算法day2】无重复字符的最长子串 两数之和
无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长 子串 的长度。
https://leetcode.cn/problems/longest-substring-without-repeating-characters/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int sub_length = 0;
vector<char> tmp = {};
for (int i = 0; i < s.size(); i++) {
bool find = false;
int j = 0;
for (; j < tmp.size(); j++) {
if (tmp[j] == s[i]) {
find = true;
break;
}
}
if (!find) {
tmp.push_back(s[i]);
} else {
if (sub_length < tmp.size()) {
sub_length = tmp.size();
}
// 找到重复的了,只好删掉vector前面的那些
for (int k = 0; k <= j; k++) {
tmp.erase(tmp.begin());
}
tmp.push_back(s[i]);
}
}
if (sub_length < tmp.size()) {
sub_length = tmp.size();
}
return sub_length;
}
};
两数之和
https://leetcode.cn/problems/two-sum/description/
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hashtable;
for(int i=0;i<nums.size() ;i++){
auto it = hashtable.find(target-nums[i]);
if(it!=hashtable.end()){
return {it->second,i};
}
hashtable[nums[i]] = i;
}
return {};
}
};