方法一:摩尔投票法
class Solution {
public:
int majorityElement(vector<int>& nums) {
int val = 0, count = 0;
for(auto &ref : nums)
{
if(!cnt) val = ref , count = 1;
else val == ref ? count ++ : count --;
}
return val;
}
};
方法二:map
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> m;
int cnt = 0, val = 0;
for(auto &ref : nums)
{
m[ref]++;
if(m[ref] > cnt){
cnt = m[ref];
val = ref;
}
}
return val;
}
};
解题步骤: 1、先从前往后遍历一遍原数组将计算的结果依次存放到这个临时数组v中
vector<int> v(n);
for(int i = 0, p = 1; i < n; i++)
{
v[i] = p;
p *= a[i];
}
2、将原来存放在v中的值取出来,从后往前遍历原数组计算他们的乘积再保存回v中
for(int i = n - 1, p = 1; i >= 0; i--)
{
v[i] *= p;
p *= a[i];
}
相当是先算左边的乘积,再算右边的乘积,最终将他们的乘积相乘再存放至v中
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
if(a.empty()) return a;
int n = a.size();
vector<int> v(n);
for(int i = 0, p = 1; i < n; i++)
{
v[i] = p;
p *= a[i];
}
for(int i = n - 1, p = 1; i >= 0; i--)
{
v[i] *= p;
p *= a[i];
}
return v;
}
};
class Solution {
public:
vector<vector<int> > findContinuousSequence(int sum) {
vector<vector<int>> res;
for(int i = 1, j = 1,s = 1; i <= sum; i++)
{
while(s < sum) s += ++j;
if(s == sum && j - i > 0)
{
vector<int> v;
for(int k = i; k <= j; k++) v.push_back(k);
res.push_back(v);
}
s -= i;
}
return res;
}
};
计算公式:(总长度 + m)% 总长度
class Solution {
public:
int lastRemaining(int n, int m) {
return n == 1 ? 0 : (lastRemaining(n - 1, m) + m) % n;
}
};
|