leetcode简单题目两道(2)
2017-04-19 23:49
344 查看
Problem
Givenaninteger,writeafunctiontodetermineifitisapowerofthree.
Followup:
Couldyoudoitwithoutusinganyloop/recursion?
Code:
classSolution{ public: boolisPowerOfThree(intn){ if(n<=0)return0; intmax_pow3=log10(INT_MAX)/log10(3); intmax_pow3_val=pow(3,max_pow3); returnmax_pow3_val%n==0; } };
说明:
自己想了好一会,居然没想到对数,,汗,这个解决方法的巧在于int最大是INT_MAX,所以取log3(INT_MAX)得到3的最大次方,然后计算出来,对n取余即可
JavaCode:
publicclassSolution{ publicbooleanisPowerOfThree(intn){ doubleres=Math.log(n)/Math.log(3); returnMath.abs(res-Math.rint(res))<0.0000000001; } }
说明:
其实和上面一样用的是对数,这就更加直接了,通过求log3(n)的结果,看与其最近的整数的差值满足几乎为0即可。
Problem:
Givenasinglylinkedlist,groupalloddnodestogetherfollowedbytheevennodes.Pleasenoteherewearetalkingaboutthenodenumberandnotthevalueinthenodes.
Required:
Youshouldtrytodoitinplace.TheprogramshouldruninO(1)spacecomplexityandO(nodes)timecomplexity.
Example:
Given1->2->3->4->5->NULL,return1->3->5->2->4->NULL.
Note:
Therelativeorderinsideboththeevenandoddgroupsshouldremainasitwasintheinput.Thefirstnodeisconsideredodd,thesecondnodeevenandsoon...
Code:
/**
*Definitionforsingly-linkedlist.
*structListNode{
*intval;
*ListNode*next;
*ListNode(intx):val(x),next(NULL){}
*};
*/
classSolution{
public:
ListNode*oddEvenList(ListNode*head){
if(head==NULL||head->next==NULL){
returnhead;
}
intcount=1;
ListNode*p,*q,*head1,*r,*tail;
head1=(structListNode*)malloc(sizeof(structListNode));
r=head1;
p=head;
q=p->next;
while(p!=NULL&&q!=NULL){
p->next=q->next;
q->next=NULL;
r->next=q;
r=q;
if(p->next==NULL){
tail=p;
}
p=p->next;
if(p!=NULL){
if(p->next==NULL){
tail=p;
}
q=p->next;
}
}
tail->next=head1->next;
returnhead;
}
};
说明:
一开始理解题目就错了,汗,看成交换奇偶了,想法是直接交换value;
指针初始化不会了,百度才知道的,汗;
没加tail指针,想直接用p作为head的最后一个指针,结果死循环了;
加了tail但是在q为NULL的时候没赋值,奇数个的时候会执行失败;
综上所述,太久没用c++了,都退化了呀。
实在是自己在写代码碰到瓶颈了,只能贴两道做过的题目了。
相关文章推荐
- leetcode简单题目两道(4)
- leetcode简单题目两道(3)
- leetcode简单题目两道(5)
- leetcode -- Invert Binary Tree -- 简单题目看看
- leetcode -- First Missing Positive -- 简单trick题目
- 【Leetcode】碰到一道脑残leetcode,比之前觉得简单的还简单。。。一下还两道……Search in Rotated Sorted Array I和II
- 异或解决LeetCode两道算法题目
- leetcode -- Text Justification -- string操作的题目,思路简单,但是难以写对
- 两道简单的题目
- leetcode 595. Big Countries(SQL,最简单的leetcode题目)38
- leetcode -- Unique Paths I &&II-- 典型DP 题目,简单要看
- 贡献两道简单的leetcode
- LeetCode中的两道动态规划题目
- leetcode -- Range Sum Query 2D - Immutable -- 简单DP题目
- Leetcode两道小题目python试水
- Leetcode--两道简单的二进制问题
- 283. Move Zeroes——LeetCode(挪“零”)(简单题目)
- leetcode题解-Dynamic Programming简单类别题目汇总
- 微软面试简单算法题目
- 简单的加密题目(公钥私钥)