1.数组中只出现一次的两个数
cpp
#include <vector>
class Solution {
public:
vector<int> FindNumsAppearOnce(vector<int>& nums) {
// write code here
int v = 0;
for(int&x:nums)
v^=x;
int cnt = 0;
while(v)
{
v>>=1;
cnt++;
}
int a = 0,b = 0;
for(int&x:nums)
{
if(x&(1<<(cnt-1)))a^=x;
else b^=x;
}
return vector<int>{min(a,b),max(a,b)};
}
};
2.求1+2+...+n
cpp
class Solution {
public:
int getSum(int n) {
return 1ll*n*(n+1)/2;
}
};
3.顺时针打印矩阵
cpp
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
int n = matrix.size();
//先排除特殊情况
if(n == 0)
return res;
//左边界
int left = 0;
//右边界
int right = matrix[0].size() - 1;
//上边界
int up = 0;
//下边界
int down = n - 1;
//直到边界重合
while(left <= right && up <= down){
//上边界的从左到右
for(int i = left; i <= right; i++)
res.push_back(matrix[up][i]);
//上边界向下
up++;
if(up > down)
break;
//右边界的从上到下
for(int i = up; i <= down; i++)
res.push_back(matrix[i][right]);
//右边界向左
right--;
if(left > right)
break;
//下边界的从右到左
for(int i = right; i >= left; i--)
res.push_back(matrix[down][i]);
//下边界向上
down--;
if(up > down)
break;
//左边界的从下到上
for(int i = down; i >= up; i--)
res.push_back(matrix[i][left]);
//左边界向右
left++;
if(left > right)
break;
}
return res;
}
};
4.扑克牌顺子
cpp
class Solution {
bool hash[14] = { 0 };
public:
bool IsContinuous(vector<int>& numbers) {
int maxVal = 0, minVal = 14;
for (int& x : numbers) {
if (x) {
if (hash[x]) return false;
hash[x] = true;
maxVal = max(maxVal, x);
minVal = min(minVal, x);
}
}
return maxVal - minVal <= 4;
}
};
5.构建乘积数组
cpp
class Solution {
public:
vector<int> multiply(vector<int>& A) {
// write code here
//看起来数值比较小,可以直接使用暴力的做法去乘
int n = A.size();
vector<int>ans(n,1);
for(int i = 0;i<n;++i)
{
for(int j = 0;j<n;++j)
{
if(j == i)continue;
ans[i] *= A[j];
}
}
return ans;
}
};
6.字符串中第一次只出现一次的字符
cpp
class Solution {
int cnt[128]{};
public:
char firstNotRepeatingChar(string s) {
for(char&c:s)
cnt[c]++;
for(char&c:s)
if(cnt[c]==1)return c;
return '#';
}
};
7.替换空格
python
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
return "%20".join(list(s.split(' ')))