剑指 Offer 03. 数组中重复的数字
- p40
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int length = nums.size();
if (length <= 0)
{
return false;
}
for (int i = 0; i < length; ++i)
{
if (nums[i] < 0 || nums[i] > length - 1)
{
return false;
}
}
for (int i = 0; i < length; ++i)
{
while (nums[i] != i)
{
if (nums[i] == nums[nums[i]])
{
return nums[i];
}
int t = nums[i];
nums[i] = nums[t];
nums[t] = t;
}
}
return false;
}
};
剑指 Offer 04. 二维数组中的查找
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if matrix == [] or matrix == [[]]:
return False
row = len(matrix)
col = len(matrix[0])
if target < matrix[0][0] or target > matrix[row-1][col-1]:
return False
r, c = 0, col-1
while r < row and c >= 0:
if matrix[r][c] == target:
return True
if matrix[r][c] < target:
r = r + 1
else:
c = c - 1
return False
剑指 Offer 05. 替换空格
class Solution {
public:
string replaceSpace(string s) {
int cnt = 0, len = s.size();
// 统计空格数量
for (char c : s)
{
if (c == ' ')
cnt++;
}
// 修改 s 长度
s.resize(len + 2 * cnt);
// 倒序遍历修改
for (int i = len - 1, j = s.size()-1; i < j; --i, --j)
{
if (s[i] != ' ')
{
s[j] = s[i];
}
else
{
s[j - 2] = '%';
s[j - 1] = '2';
s[j] = '0';
j -= 2;
}
}
return s;
}
};
剑指 Offer 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) {
stack<ListNode*> nodes;
vector<int> ans;
ListNode *pNode = head;
while (pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode->next;
}
while (!nodes.empty())
{
pNode = nodes.top();
ans.push_back(pNode->val);
nodes.pop();
}
return ans;
}
};
or
/**
* 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> ans;
reverseRec(head, ans);
return ans;
}
void reverseRec(ListNode* head, vector<int>& ans)
{
if (head != nullptr)
{
if (head->next != nullptr)
{
reverseRec(head->next, ans);
}
ans.push_back(head->val);
}
}
};