文章目录
- 1.反转链表。
- 2.判断大小端字节序
- 3.数组中的重复数字。
- 4.链表的中间节点。
- 5.删除链表的节点
- 6.二叉树的镜像
- 7.二叉树的深度
- 8.链表从尾到头打印
- 9.合并排序链表
- 10.拷贝二叉树
- 11.平衡二叉树。
- 12.二维排序数组查找
- 13.字符串替换空格
- 14.重建二叉树。
- 15.二叉树的下一个节点。
- 16.二叉树的层序遍历(广度优先遍历)。
- 17.二叉搜索树的查找/搜索。
- 18.青蛙跳台阶问题(斐波那契问题)。
- 19.剪绳子。
- 20.整型数中1的个数。
- 21. 删除排序链表中的重复元素。
- 22.奇数在前,偶数在后。
- 23.环形链表。
- 24.树的子结构
- 25.对称的 二叉树
- 26.复杂链表复制
- 27.包含min函数的栈
- 28.第一个只出现一次的字符
- 29.翻转单词顺序
- 30.排序数组中查找数字(二分)。
- 31.和为s的两个数字(双指针)
- 32.和为s的连续正数序列
- 33.两个链表的第一个公共节点(双指针,哈希)
- 34.连续子数组的最大和(动态规划)
以下代码为C/C++实现:
链表节点结构体为
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
1.反转链表。
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解题思路:直接让所有节点的next指针指向前一个节点,然后newHeader指向原链表的尾节点,返回newHeader。需要用到preNode和nextNode存储当前节点的前一个和后一个节点位置。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
2.判断大小端字节序
(大端字节序为低地址存放高位字节,小端模式为低地址存放低位字节)
union
{
short m;
char arr[sizeof(short)];
}uni;
int main()
{
uni.m = 0x0201;
if(uni.arr[0]==1 && uni.arr[1]==2)
{
printf("small--endian\n");
}
if(uni.arr[0]==2 && uni.arr[1]==1)
{
printf("big--endian\n");
}
return 0;
}
3.数组中的重复数字。
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任一一个重复的数字。不合法输入返回-1
(解体思路:每个数字都有对应的坑位,遍历整个数组,把数字放到对应的坑位上,如果数字对应的坑位已经有对应的数字了,说明重复了,返回这个重复的数字)
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int n = nums.size();
for(auto single : nums)
{
if(single <0 || single >= n)
{
return -1;
}
}
for(int i=0; i<n; i++)
{
while(nums[i] != i)
{
if(nums[i] == nums[nums[i]])
{
return nums[i];
}
swap(nums[i], nums[nums[i]]);
}
}
return -1;
}
};
3-2. 不修改数组找出重复的数字。给定一个长度为 n+1 的数组nums,数组中所有的数均在 1∼n 的范围内,其中 n≥1。请找出数组中任意一个重复的数,但不能修改输入的数组。
(思路:抽屉原理和分治的思想。本题数组下标index是苹果,数据val是抽屉。
抽屉原理:n+1 个苹果放在 n 个抽屉里,那么至少有一个抽屉中会放两个苹果。
分治思想:类似二分法)
class Solution {
public:
int duplicateInArray(vector<int>& nums) {
int l = 1, r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1; // 划分的区间:[l, mid], [mid + 1, r]
int s = 0;
for (auto x : nums)
if (x >= l && x <= mid)
s ++ ;
if (s > mid - l + 1) r = mid; //如果苹果的个数大于抽屉的个数,则至少某一个抽屉中一定有多个苹果
else l = mid + 1;
}
return r;
}
};
二分法模板(非常重要):
int bsearch_1(int l, int r)
{
while (l < r)
{
int mid = l + r >> 1;
if (check(mid)) r = mid;
else l = mid + 1;
}
return l;
}
4.链表的中间节点。
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
(解决思路:快慢指针同时指向头节点,fast向后移动两步,的同时slow向后移动一步,当fast移到NULL或者最后一个节点的时候slow移动到中间节点)
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
5.删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
(思路:需要pre和cur辅助指针,遍历链表找到后删除)
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == NULL) return head;
if(head->val == val) return head->next;
ListNode* cur = head;
ListNode* pre = NULL;
while(cur != NULL){
if(cur->val == val) pre->next = cur->next;
pre = cur;
cur = cur->next;
}
return head;
}
};
6.二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
(思路:递归)
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (root == NULL) {
return NULL;
}
mirrorTree(root->left);
mirrorTree(root->right);
swap(root->left,root->right);
return root;
}
};
7.二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
(思路:递归)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
{
return 0;
}
int lHeight = maxDepth(root->left)+1;
int rHeight = maxDepth(root->right)+1;
return max(lHeight,rHeight);
}
};
8.链表从尾到头打印
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
(思路:将链表遍历入栈,然后出栈填入数组)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
if(head == NULL)
{
return v;
}
ListNode* cur = head;
stack<int> stk;
while(cur != NULL)
{
stk.push(cur->val);
cur = cur->next;
}
while(!stk.empty())
{
v.push_back(stk.top());
stk.pop();
}
return v;
}
};
9.合并排序链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
(思路:辅助头节点dummy,按l1,l2两个链表的大小比较,进行遍历)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode;
ListNode* cur = dummy;
while(l1 != NULL && l2 !=NULL)
{
if(l1->val < l2->val)
{
cur->next = l1;
l1 = l1->next;
}else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1 != NULL) cur->next = l1;
else cur->next = l2;
return dummy->next;
}
};
10.拷贝二叉树
(思路:递归实现,先拷贝左子树,再拷贝右子树,使传入根节点的left指向左孩子,right指向右孩子)
class Solution {
public:
ListNode* mergeTwoLists(TreeNode* root) {
if (root == NULL) {
return NULL;
}
Node* lChild = copyTree(root->left);
Node* rChild = copyTree(root->right);
Node* newNode = new Node();
newNode->data = root->data;
newNode->pLChild = lChild;
newNode->pRChild = rChild;
return newNode;
}
};
11.平衡二叉树。
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
解法1(自顶向下递归)同一节点的depth函数被被递归重复调用,复杂度O(n²) 不推荐
class Solution {
public:
int depth(TreeNode *root) {
if(root == NULL){
return 0;
}
int l = depth(root->left)+1;
int r = depth(root->right)+1;
return max(l,r);
}
bool isBalanced(TreeNode* root) {
if(root == NULL){
return true;
};
bool l = isBalanced(root->left);
bool r = isBalanced(root->right);
int lDepth = depth(root->left);
int rDepth = depth(root->right);
return abs(lDepth-rDepth)<=1 && l && r;
}
};
解法2,自底向上递归,同一节点的depth函数被调用一次,复杂度O(n) 推荐
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
};
12.二维排序数组查找
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
(思路:从左上角二分,每次与target比较可以排除一行或一列,复杂度O(n+m)
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty()) return false;
int i=0,j=matrix[0].size()-1;
while(i<matrix.size() && j>=0){
if(matrix[i][j] == target) return true;
if(matrix[i][j] < target) i++;
else{
j--;
}
}
return false;
}
};
13.字符串替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"
(思路:定义新数组,遍历填入)
class Solution {
public:
string replaceSpace(string s) {
string str;
for(auto val : s){
if(val != ' ') str.push_back(val);
else str.append("%20");
}
return str;
}
};
14.重建二叉树。
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
解法一:(思路:递归,效率低)
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty()) {
return NULL;
}
TreeNode* root = new TreeNode(preorder[0]);
int index = searchIndex(preorder,inorder);
vector<int> lPreorder(preorder.begin()+1,preorder.begin()+index+1);
vector<int> lInorder(inorder.begin(),inorder.begin()+index);
TreeNode* l = buildTree(lPreorder,lInorder);
vector<int> rPreorder(preorder.begin()+index+1,preorder.end());
vector<int> rInorder(inorder.begin()+index+1,inorder.end());
TreeNode* r = buildTree(rPreorder,rInorder);
root->left = l;
root->right = r;
return root;
}
int searchIndex(vector<int>& preorder, vector<int>& inorder) {
int index=0;
for(int i=0;i<inorder.size();i++){
if(inorder[i] == preorder[0]){
index = i;
break;
}
}
return index;
}
};
解法二:(思路:通过下标判断递归出口,避免vector开辟,效率高,难理解)
class Solution {
public:
unordered_map<int,int> pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for (int i = 0; i < n; i ++ )
pos[inorder[i]] = i;
return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
}
TreeNode* dfs(vector<int>&pre, vector<int>&in, int pl, int pr, int il, int ir)
{
if (pl > pr) return NULL;
int k = pos[pre[pl]] - il;
TreeNode* root = new TreeNode(pre[pl]);
root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1);
root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir);
return root;
}
};
15.二叉树的下一个节点。
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
注意:
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;
(思路:分三种情况讨论,一、节点有右孩子,return 右孩子。二、节点为父亲的左孩子,return 父亲。三、节点为父节点的右孩子,顺着父亲找某一个节点,,满足节点为父亲的左孩子或者节点父亲为NULL结束,return 节点父亲。
第二种和第三种可以写在一起,如下)
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* p) {
if(p->right) {
p = p->right;
while(p->left) {
p = p->left;
}
return p;
}
while(p->father && p == p->father->right){
p = p->father;
}
return p->father;
}
};
16.二叉树的层序遍历(广度优先遍历)。
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
(思路:队列,将要遍历的节点入队,从队头遍历完这个节点后出队,然后将子节点入队,循环遍历直到队列为空)
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ret;
if(root == NULL) {
return ret;
}
queue<TreeNode*> queue;
queue.push(root);
while (!queue.empty())
{
int curLevelSize = queue.size();
ret.push_back(vector <int> ());
for(int i=0;i<curLevelSize;i++)
{
TreeNode* node = queue.front();
ret.back().push_back(node->val);
queue.pop();
if (node->left!= NULL)
{
queue.push(node->left);
}
if (node->right != NULL)
{
queue.push(node->right);
}
}
}
return ret;
}
};
层序遍历原版:
void orderTraverse(Node* root)
{
queue<Node*> queue;
queue.push(root);
while (!queue.empty())
{
Node* node = queue.front();
queue.pop();
cout << node->index << ": " << node->data << endl;
if (node->pRChild != NULL)
{
queue.push(node->pRChild);
}
if (node->pLChild != NULL)
{
queue.push(node->pLChild);
}
}
}
17.二叉搜索树的查找/搜索。
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
(思路:递归,细节:return serchBST() 可以返回最底层的返回值到最上层递归)
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == NULL || root->val == val)
return root;
if(val < root->val)
return searchBST(root->left,val);
return searchBST(root->right,val);
}
};
18.青蛙跳台阶问题(斐波那契问题)。
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
(思路:斐波拉契序列问题,从下往上类推f(n)=f(n-1)+f(n-2)。)
class Solution {
public:
int numWays(int n) {
if(n==0) return 1;
if(n==1) return 1;
if(n==2) return 2;
int p=1,q=2,sum=0;
for(int i=3;i<=n;i++){
sum = (p + q) % 1000000007;
p = q;
q = sum;
}
return sum;
}
};
19.剪绳子。
给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]…k[m-1] 。请问 k[0]k[1]…*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18
(思路:每段分割的绳子的长度只能为2或3,才能乘积最大)
class Solution {
public:
int cuttingRope(int n) {
if(n<=3)
return 1*(n-1);
int ret=1;
if(n%3 == 1) {
ret *= 4;
n = n - 4;
}
if(n%3 == 2) {
ret *= 2;
n = n - 2;
}
while(n!=0) {
ret *= 3;
n = n-3;
}
return ret;
}
};
20.整型数中1的个数。
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).)。
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
while(n)
{
ret += n&1;
n = n>>1;
}
return ret;
}
};
21. 删除排序链表中的重复元素。
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。
(思路:因为头节点有可能是重复元素,所以建立辅助头节点dummy,再建立辅助指针 l 指向重复元素的前一个节点,r 指向重复元素的后一个节点,让 l->next = r,也就删掉了重复节点)
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto dummy = new ListNode(-1);
dummy->next = head;
auto l = dummy; //l表示左指针,r表示右指针
while (l->next) {
auto r = l->next;
while (r && l->next->val == r->val) r = r->next;
if (l->next->next == r) l = l->next; //如果 l 的下一个元素不是重复元素
else l->next = r;
}
return dummy->next;
}
};
22.奇数在前,偶数在后。
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
if ((nums[left] % 2 ) == 1) {
left ++;
continue;
}
if ((nums[right] % 2) == 0) {
right --;
continue;
}
swap(nums[left], nums[right]);
}
return nums;
}
};
23.环形链表。
23-1.输出环形的入口节点(思路:哈希set或map)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
map<ListNode*,bool>m;
ListNode* cur = head;
while(cur != NULL)
{
if(m[cur]) break;
m[cur] = true;
cur = cur->next;
}
return cur;
}
};
23-2.给定一个链表,判断链表中是否有环。(思路:快慢指针)
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL) return false;
ListNode* slow = head;
ListNode* fast = head->next;
while(fast != NULL && fast->next != NULL)
{
if(slow == fast) return true;
fast = fast->next->next;
slow = slow->next;
}
return false;
}
};
24.树的子结构
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(A == NULL || B == NULL) return false;
return recur(A,B) || isSubStructure(A->left,B) || isSubStructure(A->right, B);
}
// 当B的根节点与A的根节点相等,且B是A的子结构,返回true
bool recur(TreeNode* A, TreeNode* B){
if(B==NULL) return true;
if(A==NULL) return false;
return A->val == B->val && recur(A->left,B->left) && recur(A->right,B->right);
}
};
25.对称的 二叉树
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
(树是对称则说明,任意对称节点的左孩子的val与右孩子的val相等,即
root->left->val = root->right->val,由此写出判断左右子树对称的递归函数recur
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) {
return true;
}
return recur(root->left,root->right);
}
bool recur(TreeNode* A, TreeNode* B){
if(A == NULL && B == NULL) return true;
if(A == NULL || B == NULL) return false;
return A->val == B->val && recur(A->left,B->right) && recur(A->right,B->left);
}
};
26.复杂链表复制
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*,Node*> m;
Node* cur = head;
while(cur != NULL){
Node* node = new Node(cur->val);
m[cur] = node;
cur = cur->next;
}
cur = head;
while(cur != NULL){
m[cur]->next = m[cur->next];
m[cur]->random = m[cur->random];
cur = cur->next;
}
return m[head];
}
};
27.包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
(思路1:辅助栈,stk1是主栈,stkMin是辅助栈,存储主栈对应的最小值元素,当有新元素入主栈,辅助栈也要插入当前栈的最小值。辅助栈和主栈同时入栈,同时出栈。辅助栈的栈顶就是主栈的最小值)
class MinStack {
public:
/** initialize your data structure here. */
stack<int>stk1;
stack<int> stkMin;
MinStack() {
}
void push(int x) {
if(stk1.empty() || stkMin.top() > x)
stkMin.push(x);
else stkMin.push(stkMin.top());
stk1.push(x);
}
void pop() {
stkMin.pop();
stk1.pop();
}
int top() {
return stk1.top();
}
int min() {
return stkMin.top();
}
};
(思路2:当 x 的值大于min时不入stkMin,比较节省空间)
class MinStack {
public:
/** initialize your data structure here. */
stack<int>stk1;
stack<int> stkMin;
MinStack() {
}
void push(int x) {
if(stk1.empty() || stkMin.top() >= x) //为了防止最小值元素有多个,必须有==
stkMin.push(x);
stk1.push(x);
}
void pop() {
if(stk1.top() == stkMin.top()) stkMin.pop(); //只有相等才说明主栈的栈顶时最小值,辅助栈才能出栈
stk1.pop();
}
int top() {
return stk1.top();
}
int min() {
return stkMin.top();
}
};
28.第一个只出现一次的字符
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
class Solution {
public:
char firstUniqChar(string s) {
int cnt[128] ;
memset(cnt,0,sizeof(int)*128);
for(auto i : s) cnt[i]++;
for(auto i : s) if(cnt[i]==1) return i;
return ' ';
}
};
29.翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。
(思路:将单词用字符分割,存入数组,再反转,再拼接成字符串)
class Solution {
public:
string reverseWords(string s) {
if (s.empty())
return "";
s += " ";
string temp = "";
vector<string> res;
for (char ch : s)
{
if (ch == ' ')
{
if (!temp.empty())
{
res.push_back(temp);
temp.resize(0);
}
}
else
temp += ch;
}
s.resize(0);
reverse(res.begin(), res.end());
for (stirng str : res)
s += str + ' ';
s.pop_back();
return s;
}
};
字符串问题模板
头和尾没空格,中间只有一个空格。
s += " ";
string temp = "";
vector<string> res;
for (char ch : s)
{
if (ch == ' ')
{
res.push_back(temp);
temp.resize(0);
}
else
temp += ch;
}
头尾有空格,单词间有多个空格
s += " ";
string temp = "";
vector<string> res;
for (char ch : s)
{
if (ch == ' ')
{
if (!temp.empty())
{
res.push_back(temp);
temp.resize(0);
}
}
else
temp += ch;
}
30.排序数组中查找数字(二分)。
统计一个数字在排序数组中出现的次数。
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.empty()) return 0;
int count = 0;
int idx = searchPos(nums,target);
if(nums[idx] != target) return 0;
for(int i=idx;i<nums.size();i++){
if(nums[i] == target) count++;
else break;
}
for(int i=idx-1;i>=0;i--){
if(nums[i] == target) count++;
else break;
}
return count;
}
int searchPos(vector<int>& nums, int target) {
int l = 0,r = nums.size()-1;
while (l < r)
{
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
return l;
}
};
31.和为s的两个数字(双指针)
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i=0,j=nums.size()-1;
while(i < j) {
int sum = nums[i] + nums[j];
if(sum < target) i++;
else if(sum == target) break;
else j--;
}
vector<int> v;
if(i>=j) return v;
v.push_back(nums[i]);
v.push_back(nums[j]);
return v;
}
};
32.和为s的连续正数序列
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
(思路,双指针,可以看作有target长度的数组,数组中的index=val,求连续元素之和等于target,代码中 i
控制连续元素的左下标指针,j
表示连续元素的右下标指针)
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> res;
for(int i=1, j=1, s=1; i < target; i++){
while(s < target) {
++j;
s += j;
}
if(s == target && j - i >0){
vector<int> line;
for(int k = i; k <= j; k++) line.push_back(k);
res.push_back(line);
}
s -= i;
}
return res;
}
};
33.两个链表的第一个公共节点(双指针,哈希)
(思路一:双指针,一个从A走,一个从B走,最终肯定在交点相遇)推荐
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA,* curB = headB;
while(curA != curB){
if(curA != NULL) curA = curA->next;
else curA = headB;
if(curB != NULL) curB = curB->next;
else curB = headA;
}
return curA;
}
};
(思路二:哈希)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
map<ListNode*,bool> m;
ListNode* curA = headA, *curB = headB;
while(curA != NULL) {
m[curA] = true;
curA = curA->next;
}
while(curB != NULL) {
if(m[curB] == true) return curB;
curB = curB->next;
}
return NULL;
}
};
34.连续子数组的最大和(动态规划)
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
(思路:通过 0下标结尾最大和,可以求以 1 下标结尾的最大和,再可以求出以 2 下标结尾的最大和,直到 n下标结尾的最大和。当前元素最大和的具体求法是, 前一个元素的最大和 >0,相加当前元素,否则 最大和为当前元素。将最大元素和记录,然后返回。)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxVal = nums[0];
int pre = nums[0];
for(int i=1;i<nums.size();i++) {
if(pre >0 ) pre = pre + nums[i];
else pre = nums[i];
maxVal = max(pre,maxVal);
}
return maxVal;
}
};