LeetCode.1-10
- LeetCode 1. The sum of two numbers
- LeetCode 2. Add two numbers
- LeetCode 3. The longest substring without repeated characters
- LeetCode 4. Find the median of two positive arrays
- LeetCode 5. The longest palindrome substring
- LeetCode 6. Zigzag transformation
- LeetCode 7. Integer Reversal
- LeetCode 8. String to Integer (atoi)
- LeetCode 9. Number of palindromes
- LeetCode 10. Regular expression matching
LeetCode 1. The sum of two numbers
哈希表实现插入查询
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>heap;
for(int i=0;i<nums.size();i++)
{
int r=target-nums[i];
if(heap.count(r)) return{
heap[r],i};
heap[nums[i]]=i;
}
return {
};
}
};
LeetCode 2. Add two numbers
2. Add two numbers .
Simulation: O (n) O(n)O ( n )
thinking: dummy is a virtual head node, t represents a carry, as long as the linked lists l1 and l2 are not empty or there is still a carry, the loop will continue.
Each time t is added to the current digits of l1, l2, l1, l2 then point to the next node.
Note: The virtual head node can avoid discussing the boundary case
C++ code:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto dummy=new ListNode(-1),cur=dummy;
int t=0;
while(l1 || l2 || t)
{
if(l1) t+=l1->val,l1=l1->next;
if(l2) t+=l2->val,l2=l2->next;
cur->next=new ListNode(t%10);
cur=cur->next;
t/=10;
}
return dummy->next;
}
};
LeetCode 3. The longest substring without repeated characters
3. The longest substring without repeated characters .
Algorithm:
double pointer scan O (n) O (n)O ( n )
idea: double pointer + hash. The
hash table stores the number of times each character in the substring in this
loop traverses each time, heap[s[i]]++, which means that in this substring The number of occurrences of the character in the string plus 1, if s[i]>1, it means that the previous character in the substring is the same as the newly added character, and the front pointer j moves backward until the occurrence of s[i]=1 and the
last update The maximum value can be
C++ code:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int>heap;
int res=0;
for(int i=0,j=0;i<s.size();i++)
{
heap[s[i]]++;
while(heap[s[i]]>1) heap[s[j++]]--;
res=max(res,i-j+1);
}
return res;
}
};
LeetCode 4. Find the median of two positive arrays
4. Find the median of two positively ordered arrays .
LeetCode 5. The longest palindrome substring
5. The longest palindrome substring .
LeetCode 6. Zigzag transformation
LeetCode 7. Integer Reversal
LeetCode 8. String to Integer (atoi)
8. Convert string to integer (atoi) .