x的平方根
题目链接:https://leetcode-cn.com/problems/sqrtx/
第一个想到的方法是二分法。
class Solution {
public:
int mySqrt(int x) {
double left=0;
double right=x;
while(int(left)<int(right))
{
double mid=left+(right-left)/2;
if(mid*mid==x)
return int(mid);
else if(mid*mid>x)
right=mid;
else
left=mid;
}
return int(left);
}
};
看参考答案,提出了牛顿迭代法。。
class Solution {
public:
int mySqrt(int x) {
if(x==0)
return 0;
double pre=2;
while(1)
{
double cur=(pre+x/pre)/2;
if(int(pre)==int(cur))
return int(pre);
else
pre=cur;
}
}
};
删除排序链表中重复元素
题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
自立更生
/**
* 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) {
if(head==NULL)
return head;
ListNode *pbefore=head;
ListNode *pcur=pbefore->next;
while(pcur)
{
if(pcur->val==pbefore->val)
{
ListNode *pnext=pcur->next;
pbefore->next=pnext;
delete pcur;
pcur=pnext;
}
else
{
pbefore=pcur;
pcur=pcur->next;
}
}
return head;
}
};
简易版本(但会内存泄漏)
/**
* 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 *cur=head;
while(cur&&cur->next)
{
if(cur->val==cur->next->val)
cur->next=cur->next->next;
else
cur=cur->next;
}
return head;
}
};
合并2个有序数组
题目链接:https://leetcode-cn.com/problems/merge-sorted-array/
注意点:
(1)注意任一个数组都可以为空,即要考虑m或n为0的情况
(2)从后往前进行比较与覆盖
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
if(m==0)
{
for(int i=0;i<n;i++)
{
nums1[i]=nums2[i];
}
return;
}
if(n==0)
return;
int len=m+n-1;
m-=1;
n-=1;
while(m>=0&&n>=0)
{
if(nums1[m]<nums2[n])
nums1[len--]=nums2[n--];
else
nums1[len--]=nums1[m--];
}
if(n>=0)
{
while(n>=0)
{
nums1[len--]=nums2[n--];
}
}
return;
}
};
相同的树
题目链接:https://leetcode-cn.com/problems/same-tree/
中序遍历的递归方法
/**
* 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==NULL&&q==NULL)
return true;
else if(p==NULL||q==NULL)
return false;
else if(p->val!=q->val)
return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};