题
数组左移
取余
class Solution {
public:
string reverseLeftWords(string s, int n) {
string ans="";
int m=s.size();
for(int i=n;i<m+n;i++)
{
ans+=s[i%m];
}
return ans;
}
};
位运算
j&1 得到尾数
只出现一次的数字
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for(auto i:nums){
//相同为0,不同为1
res^=i;
}
return res;
}
};
两数之和等于k
用unordered_map,时间复杂度降低为O(n)
动态规划
走楼梯
一次只能走一步或两步
class Solution {
public:
// Math.pow((1 + sqrt_5) / 2, n + 1) - Math.pow((1 - sqrt_5) / 2,n + 1
// 斐波那契数列
int dp[1000];
int climbStairs(int n) {
dp[0]=dp[1]=1;
for(int i=2;i<=n;i++)
{
dp[i]=dp[i-1]+dp[i-2];
// 只有走一步走两步两种
}
return dp[n];
}
};
判断回文
for (int i = 0, j = vals.size() - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
return false;
}
}
反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur){
ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};