67. 数字在排序数组中出现的次数
https://www.acwing.com/problem/content/63/
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
int ans = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] == k) ans++;
}
return ans;
}
};
68. 0到n-1中缺失的数字 (二分)
https://www.acwing.com/problem/content/64/
class Solution {
public:
int getMissingNumber(vector<int>& nums) {
if(nums.empty()) return 0;
int l = 0, r = nums.size() - 1;
while(l < r)
{
int mid = l + r >> 1;
if(nums[mid] != mid) r = mid;
else l = mid + 1;
}
if(nums[r] == r) r++;
return r;
}
};
32. 调整数组顺序使奇数位于偶数前面
https://www.acwing.com/problem/content/30/
算法
(双指针扫描) O(n)
用两个指针分别从首尾开始,往中间扫描。扫描时保证第一个指针前面的数都是奇数,第二个指针后面的数都是偶数。每次迭代时需要进行的操作:
第一个指针一直往后走,直到遇到第一个偶数为止;
第二个指针一直往前走,直到遇到第一个奇数为止;
交换两个指针指向的位置上的数,再进入下一层迭代,直到两个指针相遇为止;
时间复杂度
当两个指针相遇时,走过的总路程长度是 nn,所以时间复杂度是 O(n)。
class Solution{
public:
void reOrderArray(vector<int> &array){
int l = 0, r = array.size() - 1;
while(l < r){
while(l < r && array[l] % 2 == 1) l++;
while(l < r && array[r] % 2 == 0) r--;
if(l < r) swap(array[l],array[r]);
}
}
};
AcWing 17. 从尾到头打印链表
算法
(遍历链表) O(n)
单链表只能从前往后遍历,不能从后往前遍历。因此我们先从前往后遍历一遍输入的链表,将结果记录在答案数组中。
最后再将得到的数组逆序即可。时间复杂度分析
链表和答案数组仅被遍历了常数次,所以总时间复杂度是O(n)。
https://www.acwing.com/problem/content/18/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
while (head) {
res.push_back(head->val);
head = head->next;
}
return vector<int>(res.rbegin(), res.rend());
}
};
20. 用两个栈实现队列
https://www.acwing.com/problem/content/36/
算法
(栈,队列) O(n)
这是一道基础题,只要把功能实现对就可以,不需要考虑运行效率。我们用两个栈来做,一个主栈,用来存储数据;一个辅助栈,用来当缓存。
push(x),我们直接将x插入主栈中即可。
pop(),此时我们需要弹出最先进入栈的元素,也就是栈底元素。我们可以先将所有元素从主栈中弹出,压入辅助栈中。则辅助栈的栈顶元素就是我们要弹出的元素,将其弹出即可。然后再将辅助栈中的元素全部弹出,压入主栈中。
peek(),可以用和pop()操作类似的方式,得到最先压入栈的元素。
empty(),直接判断主栈是否为空即可。
时间复杂度分析
push():O(1);
pop(): 每次需要将主栈元素全部弹出,再压入,所以需要 O(n) 的时间;
peek():类似于pop(),需要 O(n) 的时间;
empty():O(1);
C++ 代码
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> stk, cache;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stk.push(x);
}
void copy(stack<int> &a, stack<int> &b) {
while (a.size()) {
b.push(a.top());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
copy(stk, cache);
int res = cache.top();
cache.pop();
copy(cache, stk);
return res;
}
/** Get the front element. */
int peek() {
copy(stk, cache);
int res = cache.top();
copy(cache, stk);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/