https://leetcode.com/problems/two-sum
1.Two Sum
暴力枚举
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for(int i = 0; i < nums.size(); i++){
for(int j = i+1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
res.push_back(i); res.push_back(j);
}
}
}
return res;
}
};
2.Add Two Numbers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode *l3 = NULL;
ListNode **node = &l3;
while(l1 != NULL || l2 != NULL || carry > 0){
if(l1 != NULL){
carry += l1->val;
l1 = l1->next;
}
if(l2 != NULL){
carry += l2->val;
l2 = l2->next;
}
(*node) = new ListNode(carry % 10);
carry /= 10;
node = &((*node)->next);
}
return l3;
}
};
3.Longest Substring Without Repeating Characters
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(!s.size()) return 0;
int res = 0, temp = 0;
vector<int> h(260);
for(int i = 0, j = 0; j < s.size();){
if(!h[s[j]]){
h[s[j]]++;
temp++;
j++;
}
else{
temp--;
h[s[i]]--;
i++;
}
res = res > temp ? res : temp;
}
return res;
}
};