目录
1--数组中重复的数字(03)
解决方法1:
基于哈希表,将数组中的元素视为 Key,其对应的 Value 设为 True;遍历每一个元素,查询元素 Key 对应的 Value,若为 True 表示之前已经出现了它的重复元素;否则将元素 Key 对应的 Value 设为 True,保存在哈希表中;
C++ 版本:
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
// 基于哈希表
class Solution {
public:
int findRepeatNumber(std::vector<int>& nums) {
std::unordered_map<int, bool> map;
for(int num : nums) {
if(map[num]) return num;
map[num] = true;
}
return -1;
}
};
int main(int argc, char *argv[]){
std::vector<int> v1 = {2, 3, 1, 0, 2, 5, 3};
Solution s1;
int num = s1.findRepeatNumber(v1);
std::cout << "num: " << num << std::endl;
return 0;
}
Python 版本:
from typing import List
class Solution:
def duplicate(self, numbers: List[int]) -> int:
hash_set = set()
for number in numbers:
if(number in hash_set):
return number
else:
hash_set.add(number)
return -1
if __name__ == "__main__":
test = [2, 3, 1, 0, 2, 5, 3]
S1 = Solution()
res = S1.duplicate(test)
print(res)
解决方法2:
利用原地交换,将索引位置 i 与位置上的值 nums[i] 匹配上;
题解的一个易懂解释:
这个原地交换法就相当于分配工作,每个索引代表一个工作岗位,每个岗位必须专业对口,既0索引必须0元素才能上岗。而我们的目的就是找出溢出的人才,既0索引岗位有多个0元素竞争。
我们先从0索引岗位开始遍历,首先我们看0索引是不是已经专业对口了,如果已经专业对口既nums[0]=0,那我们就跳过0岗位看1岗位。如果0索引没有专业对口,那么我们看现在0索引上的人才调整到他对应的岗位上,比如num[0]=2,那我们就把2这个元素挪到他对应的岗位上既num[2],这个时候有两种情况:1、num[2]岗位上已经有专业对口的人才了,既num[2]=2,这就说明刚刚那个在num[0]上的2是溢出的人才,我们直接将其返回即可。2、num[2]上的不是专业对口的人才,那我们将num[0]上的元素和num[2]上的元素交换,这样num[2]就找到专业对口的人才了。之后重复这个过程直到帮num[0]找到专业对口的人才,然后以此类推帮num[1]找人才、帮num[2]找人才,直到找到溢出的人才。
C++ 版本:
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
// 核心思路是使索引位置i 与 位置i上的值nums[i]相等
class Solution {
public:
int findRepeatNumber(std::vector<int>& nums) {
int i = 0;
while(i < nums.size()){
if(nums[i] == i){ // 当前索引的位置i 与 位置的值nums[i] 相等
i++;
continue; // 无须进行后面的交换操作
}
if(nums[nums[i]] == nums[i]) return nums[i];
else std::swap(nums[i], nums[nums[i]]); // 交换
}
return -1;
}
};
int main(int argc, char *argv[]){
std::vector<int> v1 = {2, 3, 1, 0, 2, 5, 3};
Solution s1;
int num = s1.findRepeatNumber(v1);
std::cout << "num: " << num << std::endl;
return 0;
}
Python版本:
from typing import List
class Solution:
def duplicate(self, numbers: List[int]) -> int:
for i in range(len(numbers)):
if(numbers[i] == i): continue
elif(numbers[numbers[i]] == numbers[i]):
return numbers[i]
else:
self.swap(numbers, i, numbers[i])
return -1
#交换函数
def swap(self, numbers: List[int], a: int, b: int):
temp = numbers[a]
numbers[a] = numbers[b]
numbers[b] = temp
if __name__ == "__main__":
test = [2, 3, 1, 0, 2, 5, 3]
S1 = Solution()
res = S1.duplicate(test)
print(res)
2--二维数组中的查找(04)
暴力法求解:
遍历每一个一维数组,通过STL标准库 find() 函数寻找目标整数;
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
bool findNumberIn2DArray(std::vector<std::vector<int>>& matrix, int target) {
for(auto it1 = matrix.begin(); it1 != matrix.end(); it1++){
auto loc = find((*it1).begin(), (*it1).end(), target);
if(loc != (*it1).end())
return true;
}
return false;
}
};
int main(int argc, char *argv[]){
std::vector<int> m1 = {1, 4, 7, 11, 15};
std::vector<int> m2 = {2, 5, 8, 12, 19};
std::vector<int> m3 = {3, 6, 9, 16, 22};
std::vector<int> m4 = {10, 13, 14, 17, 24};
std::vector<int> m5 = {18, 21, 23, 26, 30};
std::vector<std::vector<int>> matrix = {m1, m2, m3, m4, m5};
Solution s1;
bool stat1 = s1.findNumberIn2DArray(matrix, 5);
bool stat2 = s1.findNumberIn2DArray(matrix, 20);
std::cout << "stat1: " << stat1 << std::endl;
std::cout << "stat2: " << stat2 << std::endl;
return 0;
}
搜索树解法:
将矩阵逆时针旋转 45°,将其转化为图的形式,其搜索等价于二叉搜索树,具体见题解;
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
bool findNumberIn2DArray(std::vector<std::vector<int>>& matrix, int target) {
int i = matrix.size() - 1, j = 0;
while(i >= 0 && j < matrix[0].size())
{
if(matrix[i][j] > target) i--;
else if(matrix[i][j] < target) j++;
else return true;
}
return false;
}
};
int main(int argc, char *argv[]){
std::vector<int> m1 = {1, 4, 7, 11, 15};
std::vector<int> m2 = {2, 5, 8, 12, 19};
std::vector<int> m3 = {3, 6, 9, 16, 22};
std::vector<int> m4 = {10, 13, 14, 17, 24};
std::vector<int> m5 = {18, 21, 23, 26, 30};
std::vector<std::vector<int>> matrix = {m1, m2, m3, m4, m5};
Solution s1;
bool stat1 = s1.findNumberIn2DArray(matrix, 5);
bool stat2 = s1.findNumberIn2DArray(matrix, 20);
std::cout << "stat1: " << stat1 << std::endl;
std::cout << "stat2: " << stat2 << std::endl;
return 0;
}
Python版本:
from typing import List
class Solution:
def Find(self , target: int, array: List[List[int]]) -> bool:
n = len(array)
m = len(array[0])
start_i = 0
start_j = m -1
while(start_i < n and start_j >= 0):
if(array[start_i][start_j] == target): return True
elif(array[start_i][start_j] > target): start_j -= 1
else: start_i += 1
return False
if __name__ == "__main__":
# 7, [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
target = 7
array = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
S1 = Solution()
res = S1.Find(target, array)
print(res)
3--替换空格(05)
原地修改:
不新建字符串,遍历输入的字符串,判断字符是否等于空格,是空格则删除,并插入“%20”,遍历后移3位,最后返回原字符串;
#include <iostream>
#include <string>
class Solution {
public:
std::string replaceSpace(std::string s) {
for (int i = 0; i < s.size(); i++){
if (s[i] == ' '){
s.erase(i, 1);
s.insert(i, "%20");
i = i + 2;
}
}
return s;
}
};
int main(int argc, char *argv[]){
std::string s1 = "We are happy.";
Solution Func;
std::string s2 = Func.replaceSpace(s1);
std::cout << "s2: " << s2 << std::endl;
}
新建字符串:
遍历输入的字符串,判断当前字符是否等于空格,是空格则新字符串添加“%20”,否则添加当前字符,最后返回新字符串;
#include <iostream>
#include <string>
class Solution {
public:
std::string replaceSpace(std::string s) {
std::string s1;
for(auto item : s){
if (item == ' ') s1 = s1 + "%20";
else s1 = s1 + item;
}
return s1;
}
};
int main(int argc, char *argv[]){
std::string s1 = "We are happy.";
Solution Func;
std::string s2 = Func.replaceSpace(s1);
std::cout << "s2: " << s2 << std::endl;
}
Python版本:
class Solution:
def replaceSpace(self , s: str) -> str:
res = ""
for char in s:
if char == ' ':
res += "%20"
else: res += char
return res
if __name__ == "__main__":
str = "We Are Happy"
S1 = Solution()
res = S1.replaceSpace(str)
print(res)
4--从尾到头打印链表(06)
借助STL中 vector 的 insert() 函数,遍历链表时每次都在开头插入新的元素:
#include <iostream>
#include <vector>
struct ListNode {
ListNode(){}; // 构造函数
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
std::vector<int> reversePrint(ListNode* head) {
std::vector<int> v1;
ListNode* pos = head;
while(pos != NULL){
v1.insert(v1.begin(), pos->val);
pos = pos -> next;
}
return v1;
}
};
int main(int argc, char *argv[]){
ListNode *head = new ListNode(1);
ListNode *node1 = new ListNode(3);
ListNode *node2 = new ListNode(2);
head->next = node1;
node1->next = node2;
Solution s1;
std::vector<int> v1 = s1.reversePrint(head);
for(auto item : v1){
std::cout << "item: " << item << std::endl;
}
}
分析题目,先遍历出现的元素后返回,即先进后出,符合栈的规律,可借助递归实现,递归终止的条件是当前结点的指针为空;
#include <iostream>
#include <vector>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
std::vector<int> reversePrint(ListNode* head) {
if(!head)
return {};
std::vector<int> a = reversePrint(head->next);
a.push_back(head->val);
return a;
}
};
int main(int argc, char *argv[]){
ListNode *head = new ListNode(1);
ListNode *node1 = new ListNode(3);
ListNode *node2 = new ListNode(2);
head->next = node1;
node1->next = node2;
Solution s1;
std::vector<int> v1 = s1.reversePrint(head);
for(auto item : v1){
std::cout << "item: " << item << std::endl;
}
}
Python版本:
import sys
from typing import List
#设置递归深度
sys.setrecursionlimit(100000)
class ListNode:
def __init__(self, val=0, next = None):
self.val = val
self.next = next
class Solution:
def recursion(self, head: ListNode, res: List[int]):
if head:
self.recursion(head.next, res)
res.append(head.val)
def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
res = []
self.recursion(listNode, res)
return res
if __name__ == "__main__":
# {1,2,3}
Node1 = ListNode(1)
Node2 = ListNode(2)
Node3 = ListNode(3)
Node1.next = Node2
Node2.next = Node3
S1 = Solution()
res = S1.printListFromTailToHead(Node1)
print(res)
5--重建二叉树(07)
主要思路:
前序遍历第一个肯定是根节点,中序遍历根节点左边是左子树,右边是右子树;
因此,在中序遍历定位根节点的位置后,可以递归处理左子树和右子树;
左子树和右子树的起始和结束位置可以根据左子树的大小确定;
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for(int i = 0; i < n; i++){
m1[inorder[i]] = i;
}
TreeNode* Tree = mybuildTree(preorder, inorder, 0, n-1, 0, n-1);
return Tree;
}
TreeNode* mybuildTree(vector<int>& preorder, vector<int>& inorder, int p_start, int p_end,
int i_start, int i_end){
if( p_start > p_end){
return nullptr;
}
TreeNode *Root = new TreeNode(preorder[p_start]);
int Root_idx = m1[preorder[p_start]];
int left_tree_size = Root_idx - i_start;
Root->left = mybuildTree(preorder, inorder, p_start+1, p_start+left_tree_size,
i_start, Root_idx-1);
Root->right = mybuildTree(preorder, inorder, p_start+1+left_tree_size, p_end, Root_idx+1, i_end);
return Root;
}
std::map<int, int> m1;
};
Python版本:
from typing import List
from queue import Queue
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def reConstructBinaryTree(self , preOrder: List[int], vinOrder: List[int]) -> TreeNode:
return self.dfs(preOrder, vinOrder, 0, len(preOrder) - 1, 0, len(vinOrder) - 1)
def dfs(self, preOrder: List[int], vinOrder: List[int], pre_start: int, pre_end: int, vin_start: int, vin_end: int) -> TreeNode:
if(pre_start > pre_end): return None
root = TreeNode(preOrder[pre_start]) # 取根节点
i = vin_start # 中序遍历中计算根节点的位置
while(i <= vin_end):
if(vinOrder[i] == root.val):
break # 根节点的位置
i += 1
# 计算左子树的长度
left_num = i - vin_start
# 递归构建左子树和右子树
root.left = self.dfs(preOrder, vinOrder, pre_start + 1, pre_start + left_num, vin_start, i - 1)
root.right = self.dfs(preOrder, vinOrder, pre_start + left_num + 1, pre_end, i + 1, vin_end)
return root
if __name__ == "__main__":
# [1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6]
S1 = Solution()
pre = [1, 2, 4, 7, 3, 5, 6, 8]
vin = [4, 7, 2, 1, 5, 3, 8, 6]
res = S1.reConstructBinaryTree(pre, vin)
q1 = Queue()
q1.put(res)
while(not q1.empty()):
cur = q1.get()
print(cur.val)
if(cur.left != None):
q1.put(cur.left)
if(cur.right != None):
q1.put(cur.right)
6--用两个栈实现队列(09)
建立两个栈,一个作为输入栈,一个作为输出栈;输出队列时,直接返回输出栈的栈顶元素;当输出栈为空时,如果输入栈不会空,就把输入栈的元素移动到输出栈中;如果输入栈也为空则表示队列为空,返回-1;
class CQueue {
public:
CQueue() {
}
void appendTail(int value) {
in_stack.push(value);
}
int deleteHead() {
if (out_stack.size() != 0){
elem = out_stack.top();
out_stack.pop();
return elem;
}
else{
if(in_stack.size() == 0){
return -1;
}
else{
int instack_size = in_stack.size();
for(int i = 0; i < instack_size; i++){
elem = in_stack.top();
out_stack.push(elem);
in_stack.pop();
}
elem = out_stack.top();
out_stack.pop();
return elem;
}
}
}
std::stack<int> in_stack;
std::stack<int> out_stack;
int elem;
};
Python版本:
class Solution:
def __init__(self):
self.stack1 = [] # 输入栈
self.stack2 = [] # 输出栈
def push(self, node):
self.stack1.append(node)
def pop(self):
if(len(self.stack2) == 0):
if(len(self.stack1) == 0): return -1
else:
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
if __name__ == "__main__":
S1 = Solution()
S1.push(1)
S1.push(2)
print(S1.pop())
print(S1.pop())
print("all done!")
7--斐波拉契数列(10)
经典动态规划题目,使用递归会导致内存消耗大、运行时间长等问题,利用递推的方式实现求解:从 F(2) = F(1) + F(0) 开始递推,利用变量记录当前的F(N-1)和F(N-2);
class Solution {
public:
int fib(int n) {
if (n < 2){
return n;
}
int f_1 = 0, f_2 = 0, sum = 1;
for(int i = 2; i <= n; i++){
f_2 = f_1;
f_1 = sum;
sum = (m1 + m2) % 1000000007;
}
return sum;
}
};
Python版本:
class Solution:
def Fibonacci(self , n: int) -> int:
if(n == 1 or n == 2): return 1
res = 1
pre1 = 1
pre2 = 1
for i in range(n - 2):
res = pre1 + pre2
pre2 = pre1
pre1 = res
return res
if __name__ == "__main__":
S1 = Solution()
print(S1.Fibonacci(4))
print("all done!")
8--青蛙跳台阶问题(10)
设 n 阶台阶有 f(n) 种跳法,假设最后一步只跳一阶,则剩下的 n-1 个台阶有 f(n-1) 种跳法;假设最后一步跳两阶,则剩下的 n-2 个台阶有 f(n-2) 种跳法;即 f(n) = f(n-1) + f(n-2);
边界条件:f(0) = 1;f(1) = 1;f(2) = 2;
class Solution {
public:
int numWays(int n) {
int f1 = 1, f2 = 0, sum = 1;
for(int i = 0; i < n; i++){
sum = (f1 + f2) % 1000000007;
f2 = f1;
f1 = sum;
}
return sum;
}
};