剑指 Offer 03. 数组中重复的数字
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
vector<int> hash(n, 0);
for(int i = 0; i < n; ++i) {
hash[nums[i]]++;
if(hash[nums[i]] > 1) return nums[i];
}
return 0;
}
};
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 || matrix[0].size() == 0) return false;
int n = matrix.size();
int m = matrix[0].size();
int i = n - 1, j = 0;
while(i >= 0 && j < m) {
if(target == matrix[i][j]) return true;
else if(target > matrix[i][j]) {
j++;
}
else {
i--;
}
}
return false;
}
};
class Solution {
public:
//c++ 字符串string自带函数 erase insert等,
string replaceSpace(string s) {
for(int i = 0; i < s.size(); ++i) {
if(s[i] == ' ') {
s.erase(i, 1);//从第i个位置开始删除k个字符
s.insert(i, "%20");//从第i个位置插入string字符
}
}
return s;
}
};
/**
* 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) {
stack<int> mystack;
while(head != NULL) {
mystack.push(head -> val);
head = head -> next;
}
vector<int> ans;
while(!mystack.empty()) {
int x = mystack.top();
mystack.pop();
ans.push_back(x);
}
return ans;
}
};
//递归流批
class Solution {
public:
vector<int> ans;
void recur(ListNode* head) {
if(head == NULL) return;
recur(head -> next);
ans.push_back(head -> val);
}
vector<int> reversePrint(ListNode* head) {
recur(head);
return ans;
}
};