招商银行信用卡
21. 合并两个有序链表
直接模拟一遍即可,不需要新建结点,直接修改每个结点指向即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* head = new ListNode(-1);
if (!list1 && !list2) return nullptr;
head -> next = nullptr;
auto cur = head;
while (list1 && list2) {
if (list1->val <= list2->val) {
cur->next=list1;
cur = cur->next;
list1=list1->next;
}
else {
cur->next=list2;
cur = cur->next;
list2=list2->next;
}
}
if (list1) cur->next = list1;
if (list2) cur->next = list2;
return head->next;
}
};
3. 无重复字符的最长子串
开一个数组或者哈希存储滑动窗口中字母出现的次数
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> mp;
int res = 0;
for (int i = 0, j = 0; i < s.size(); i ++ ) {
mp[s[i]] ++ ;
while (mp[s[i]] > 1) -- mp[s[j ++ ]];
res = max(res, i - j + 1);
}
return res;
}
};
322. 零钱兑换
f[i][j]
表示考虑前i
种货币,凑成j
金额需要的张数最小值,递推就是第
i
i
i种货币使用几张,通过f[i][j-w]
优化的一道完全背包问题变形
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<int> f(amount + 1, 0x3f3f3f3f);
f[0] = 0;
for (int i = 0; i < n; i ++ )
{
int w = coins[i];
for (int j = w; j <= amount; j ++ )
f[j] = min(f[j], f[j - w] + 1);
}
if (f[amount] == 0x3f3f3f3f) return -1;
return f[amount];
}
};
编程能力
896. 单调数列
记录升和降是否存在,如果同时升降存在返回false
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
int n = nums.size();
if (n <= 2) return true;
bool up = false, down = false;
for (int i = 0; i < n - 1; i ++ )
if (nums[i + 1] > nums[i]) up = true;
else if (nums[i + 1] < nums[i]) down = true;
return !(up && down);
}
};
28. 实现 strStr()
首先考虑边界,如果
n
e
e
d
l
e
needle
needle空返回0,如果
h
a
y
s
t
a
c
k
haystack
haystack为空返回-1,调用substr
函数判断是否包含
n
e
e
d
l
e
needle
needle
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size();
if (!m) return 0;
else if (!n) return -1;
for (int i = 0; i + m - 1 < n; i ++ )
if (haystack.substr(i, m) == needle)
return i;
return -1;
}
};