一、丢失的数据
- 题目
- 题解
方法一(数学整数相减):
class Solution {
public:
int missingNumber(vector<int>& v) {
int n=v.size();
int sum=n*(n+1)/2;
int total=accumulate(v.begin(),v.end(),0);
return sum-total;
}
};
方法二(遍历):
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size(),i=0;
sort(nums.begin(),nums.end());
while(n>0){
if(nums[i]==i) n--,i++;
else{
break;
}
}
return i;
}
};
方法三(哈希):
class Solution {
public:
int missingNumber(vector<int>& v) {
unordered_set<int>us;
int n =v.size();
for(auto&s:v){
us.insert(s);
}
int k=-1;
for(int i=0;i<=n;i++){
if(!us.count(i)){
k=i;
break;
}
// cout<<*us.find(i);
}
return k;
}
};
方法四(位运算):
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = 0;
int n = nums.size();
for (int i = 0; i < n; i++) {
res ^= nums[i];
}
for (int i = 0; i <= n; i++) {
res ^= i;
}
return res;
}
};
范围求和 II
- 题目:
- 题解
class Solution {
public:
int maxCount(int m, int n, vector<vector<int>>& ops) {
int mina = m, minb = n;
for (const auto& op: ops) {
mina = min(mina, op[0]);
minb = min(minb, op[1]);
}
return mina * minb;
}
};
外观数列
- 题目:
- 题解:
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1";
string strCallBack=countAndSay(n-1);
int times=0;
char s=strCallBack[0];
string callBack;
for(int i=0;i<strCallBack.size();i++){
if(strCallBack[i]==s){
times++;
}else{
callBack+=to_string(times)+strCallBack[i-1];
times=1;
s=strCallBack[i];
}
if(i==strCallBack.size()-1){
callBack+=to_string(times)+strCallBack[i];
}
}
return callBack;
}
组合总和
- 题目
- 题解
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
if (sum == target) {
result.push_back(path);
return;
}
// 如果 sum + candidates[i] > target 就终止遍历
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, sum, i);
sum -= candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(), candidates.end()); // 需要排序
backtracking(candidates, target, 0, 0);
return result;
}
};