两数之和
方法1:暴力法
思想:双重for循环直接遍历数组元素,找到target数值。找不到则返回false。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res(2);
if (nums.empty())return res;
int length = nums.size();
for(int i = 0;i<length;i++){
for(int j = i+1;j<length;j++){
if(nums[i]+nums[j] == target){
res[0] = i;
res[1] = j;
}
}
}
return res;
}
};
耗时时间很长,不推荐使用该方法。
方法2:哈希表
创建一个哈希表,然后循环一次,寻找target。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> ans;
for(int i = 0;i<nums.size();i++){
int num = nums[i];
auto pos = hash.find(target - num);
if(pos == hash.end()){
hash[num] = i;
}else {
ans.push_back(pos->second);//ans入栈操作
ans.push_back(i);//ans入栈操作
break;
}
}
return ans;
}
};
效率高,时间短,推荐使用。
实现strStr
暴力强解法:
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
for (int i = 0; i + m <= n; i++) {
bool flag = true;
for (int j = 0; j < m; j++) {
if (haystack[i + j] != needle[j]) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
};