罗列一些常用算法(不定期更新):
- 双指针-快慢指针
- 摩尔投票算法
1.双指针-快慢指针
// 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (val != nums[fastIndex]) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
2.摩尔投票算法(求众数)
// 摩尔投票算法
int majorityElement(int* nums, int numsSize) {
int count = 0;
int candidate = 0;
for (int i = 0; i < numsSize; i++) {
if (count == 0) {
candidate = nums[i];
}
count += (nums[i] == candidate) ? 1 : -1;
}
return candidate;
}