1. 两数之和
利用map容器“一对一”记录两数关系. 主要思路是查找对偶数other是否被记录, 如果无,则将当前元素作为对偶数存入map;如果存在对偶数,则返回二者的索引. 时间复杂度 , 空间复杂度
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
map<int, int> record;
for(int i=0; i<nums.size(); i++)
{
int other = target - nums[i];
if(record.count(other))
{
return {i, record[other]};
}
else
{
other = nums[i];
record[other] = i;
}
}
return {-1,-1};
}
};
2. 两数相加
考虑创建哑节点dummy,使用dummy->next表示真正的头节点,避免空边界. 时间复杂度
/**
* 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) {
ListNode* first = new ListNode(0); // 哑结点
ListNode* last = first;
int carry = 0;
while(l1 or l2 or carry){
// 相加
int bitsum = 0;
if(l1){
bitsum += l1->val;
l1 = l1->next;
}
if(l2){
bitsum += l2->val;
l2 = l2->next;
}
if(carry){
bitsum += carry;
}
// 结果
int digit = bitsum % 10;
carry = bitsum / 10;
// 链表存储
ListNode* node = new ListNode(digit);
last->next = node;
last = node;
}
last = first->next;
delete first;
return last;
}
};
3. 无重复字符的最长子串
以滑动窗口的方式来寻找子串, 左指针在遇到重复元素时更新, 右指针即遍历指针i. 时间复杂度
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = l = r = 0
while r<len(s):
if s[r] not in s[l:r]:
r += 1
length = max(length, r-l)
else:
l += 1
return length
用python做算法实现,效率不高,但是很好理解。