- leetcode题目
1.1. 题目描述
1.2知识点及思路
1.3代码 - 总结
一.leetcode题目
1.Determine whether an integer is a palindrome. Do this without extra space.
题目描述:判断一个整数是否是回文,不能用额外的空间
知识点:数字最低与最高位取法;二分查找[思想]
思路:①求得整数位数n,②判断条件是最高位(num/pow(10,n)%10)是否等于最低位(num/1%10) ③二分迭代 注:num为输入整数
代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
if (x < 10)
return true;
int digits = 0;
int t = x;
int d = 0;
while(t != 0) t /= 10, ++d;
int left = pow(10, d - 1);
int right = 1;
while( left >= right)
{
if (x / left % 10 != x / right % 10)
return false;
left /= 10;
right *= 10;
}
return true;
}
};
2.Given a singly linked list, determine if it is a palindrome.
题目描述:给定一个单链表,判断其值是否是回文,要求为时间复杂度O(n),空间复杂度O(1)
知识点:链表翻转;链表中间结点;二分查找[思想];分和[思想]
思路:①查找链表的中间结点②翻转单链表后半部分③依次比较两个链表
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* reverseList(ListNode* head)
{
if(!head || !head->next)
return head;
return reverse(head, NULL);
}
ListNode* reverse(ListNode* head, ListNode* add)
{
if(head == NULL)
return add;
ListNode* temp = head->next;
head->next = add;
return reverse(temp, head);
}
public:
bool isPalindrome(ListNode* head)
{
if(!head)
return true;
if(!head->next)
return true;
ListNode *fast,*slow;
fast=slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
}
if(!fast)
slow=reverseList(slow);
else//结点为奇数
slow=reverseList(slow->next);
ListNode*p=slow;
ListNode*q=head;
while(p)
{
if(p->val==q->val)
{
p=p->next;
q=q->next;
}
else
return false;
}
return true;
}
};
3.Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
题目描述:给定一棵二叉树,进行层次遍历
知识点:二叉树的先序遍历;广度优先遍历(BFS)
思路:①先序遍历二叉树,同时②用队列保存其中的值③队列是否为空作为结束条件 注:leetcode题目当中并非简单输出其顺序,要用两个队列,严格按照分析的顺序执行出队入队操作,方可AC
代码如下:
/**
* 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:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<int>temp;
queue<TreeNode*>sto;
vector<vector<int>>result;
if(!root)
return result;
sto.push(root);
TreeNode*tempNode=NULL;
while(!sto.empty())
{
temp.clear();
queue<TreeNode*>q2;
while(!sto.empty())
{
tempNode=sto.front();
sto.pop();
temp.push_back(tempNode->val);
if(tempNode->left)
q2.push(tempNode->left);
if(tempNode->right)
q2.push(tempNode->right);
}
result.push_back(temp);
sto=q2;
}
return result;
}
};
如下为python代码:
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:return []
stack,queue,res,nCount=[root],[],[[root.val]],1
while stack:
temp=stack.pop(0)
if temp.left:
stack.append(temp.left)
if temp.right:
stack.append(temp.right)
nCount-=1
if nCount==0:
queue=[[x.val for x in stack]]
res+=queue
nCount=len(stack)
res.pop(-1)
return res
二.总结
I.编程问题一般都有些小技巧,故不急跬步,无以至千里II.让我们一同努力,明天会更好!