83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
Solution in C++:
- 关键点:删除时指针挪动的时机 && 比较顺序
- 思路:顺序扫描链表,当前位置与下一位置的元素进行对比,相同则删除,不同就继续。逻辑搞清楚,没什么难度。
/**
- Definition for singly-linked list.
- struct ListNode {
- int val;
- ListNode *next;
- ListNode(int x) : val(x), next(NULL) {}
- };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* ptr = head;
if(ptr == nullptr)
return head;
while(ptr->next){
if(ptr->val == ptr->next->val)
{
ListNode *tmp = ptr->next;
ptr->next = ptr->next->next;
free(tmp);
} else{
ptr = ptr->next;
}
}
return head;
}
};
88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Solution in C++:
- 关键点:覆盖nums1中的值,而不是插入新值
- 思路:如果nums2中的值比nums1小时一定需要将nums1中的值向后挪动,当不需要挪动的时候,一定是nums2的值大于nums1中最后一个值时。扫描nums1中的输入值,每次比较需要往后挪动的时候将nums1的真实大小m+1,当i扫到nums1最后一个值时,将nums2赋值给nums1最后一个值之后,接下来如果nums2还剩余元素,直接赋值给nums1中的后续元素。
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
size_t i, j;
size_t size = nums1.size();
for(i = 0, j = 0; i < m && j < n; ++i)
{
if(nums1[i] > nums2[j]){
for(int k = m; k > i; --k){
nums1[k] = nums1[k-1];
}
nums1[i] = nums2[j];
++m;
++j;
} else if((nums1[i] < nums2[j]) && (i==m-1)){
nums1[++i] = nums2[j];
++j;
}
}
if(i >= m) // nums1输入长度小于nums2
{
while(j != n){
nums1[i] = nums2[j];
++j;
++i;
}
}
}
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
Solution in C++:
- 关键点:树的遍历
- 思路:按树完全遍历,如果结点指针不是都为空就说明结构不一致,如果对应位置值不一致也不是相同的树。标☆的代码处,因为要遍历完树的所有部分才能return true,所以不能把这里写上如果值相同就return true
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr)
return true;
else if(p == nullptr || q == nullptr)
return false;
// 值相同且位置相同
if( p->val != q->val ) // ☆
return false;
bool left = isSameTree(p->left,q->left);
bool right = isSameTree(p->right,q->right);
return left && right;
}
};
小结
nice day,虽然第二题的一点逻辑搞了很久,但是今天总的来说都是自己码的代码,还是有点成就感的。然后还复习了几个知识点。
知识点总结
- 链表遍历及操作
- vector操作(这里我复习了insert的用法,虽然最终的代码没体现)
- 树的遍历及递归函数