剑指 Offer 03. 数组中重复的数字
分析:
哈希表保存数字出现的次数,如果当前次数大于1就返回。
代码:
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
map<int, int> mp;
for(int x : nums) {
mp[x]++;
if(mp[x] > 1) {
return x;
}
}
return -1;
}
};
剑指 Offer 09. 用两个栈实现队列
分析:
一个栈s1负责插入操作,另一个栈s2负责删除操作。入队时往s1中压入元素,则栈底始终是队头。要出队时将栈s1中元素依次出栈,然后依次压入s2,则s2的栈顶为队头,然后s2栈顶出栈,即为出队操作。如果下一次出队时s2不为空,直接出栈。
代码:
class CQueue {
public:
stack<int> s1, s2;
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if(!s2.empty()) {
int t = s2.top();
s2.pop();
return t;
}else {
while(!s1.empty()) {
int x = s1.top();
s1.pop();
s2.push(x);
}
if(s2.empty()) {
return -1;
}else {
int y = s2.top();
s2.pop();
return y;
}
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
剑指 Offer 04. 二维数组中的查找
分析:
有序数组的查找联想到二分法。将初始位置定位到右上角,如果当前值等于目标值则返回;如果大于目标值则列数减一;如果小于目标值则行数加一。
代码:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 || matrix[0].size() == 0) {
return false;
}
int m = matrix.size(), n = matrix[0].size();
int row = 0, column = n - 1;
while(row < m && column >= 0) {
int x = matrix[row][column];
if(x == target) {
return true;
}else if(x > target) {
column--;
}else {
row++;
}
}
return false;
}
};
剑指 Offer 12. 矩阵中的路径
分析:
dfs求路径,背模板。
代码:
class Solution {
private:
int m, n;
int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
vector<vector<int>> visited;
bool in(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
bool dfs(vector<vector<char>>& board, string word, int i, int j, int k) {
if(!in(i, j) || word[k] != board[i][j] || visited[i][j]) {
return false;
}
if(k == word.size() - 1) {
return true;
}
visited[i][j] = 1;
for(int t = 0; t < 4; t++) {
int x = i + dirs[t][0];
int y = j + dirs[t][1];
if(dfs(board, word, x, y, k + 1)) {
return true;
}
}
visited[i][j] = 0;//回溯
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
m = board.size(), n = board[0].size();
visited = vector<vector<int>>(m, vector<int>(n, 0));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(dfs(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
};