题目来源:力扣《剑指Offer》第二版
完成时间:2022/07/21
03. 数组中重复的数字
我的题解
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> check(nums.size());
for (int i = 0;i < nums.size(); i++){
if(check[nums[i]] == 1){
return nums[i];
}
check[nums[i]] = 1;
}
return -1;
}
};
04. 二维数组中的查找
我的题解
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0){
return false;
}
int x = matrix[0].size() - 1,y = 0;
while(x >= 0 && y < matrix.size()){
if(matrix[y][x] == target){
return true;
}else if(matrix[y][x] > target){
x--;
}else {
y++;
}
}
return false;
}
};
05. 替换空格
我的题解
class Solution {
public:
string replaceSpace(string s) {
string r = "";
for(int i = 0;i < s.size();i++) {
if(s[i] == ' '){
r += "%20";
}else {
r += s[i];
}
}
return r;
}
};
06. 从尾到头打印链表
我的题解
常规方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> result;
while(head != nullptr) {
result.push_back(head->val);
head = head->next;
}
reverse(result.begin(),result.end());
return result;
}
};
递归实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//递归实现
void check(vector<int>& result,ListNode* node) {
if(node->next != nullptr){
check(result,node->next);
}
result.push_back(node->val);
}
vector<int> reversePrint(ListNode* head) {
vector<int> result;
if(head != nullptr)
check(result,head);
return result;
}
};