您的位置:首页 > 其它

leetCode刷题记录

2014-03-26 17:02 183 查看
(1)LinkedListCycle
TotalAccepted:13297TotalSubmissions:38411
Givenalinkedlist,determineifithasacycleinit.
Followup:
Canyousolveitwithoutusingextraspace?
(url:http://oj.leetcode.com/problems/linked-list-cycle/)

/**
*Definitionforsingly-linkedlist.
*classListNode{
*intval;
*ListNodenext;
*ListNode(intx){
*val=x;
*next=null;
*}
*}
*/
publicclassSolution{
publicbooleanhasCycle(ListNodehead){
if(head==null){
returnfalse;
}
ListNodetemp=head;
ListNodehold=head;
while(temp!=null){
if(temp.next==null){
returnfalse;
}
else{
if(temp.next==head){
returntrue;
}
}
hold=temp;
temp=temp.next;
hold.next=head;
}
returnfalse;
}
}
[/code]
2,如果原有数据list中node有其他存储空间,例如有空余的属性值可以使用该属性值作为标志位来区别访问前的访问后的节点。

3,如果能够确定node里面的节点属于某一个范围。则可以利用数字的大小来做为标识位。在数的大小范围很小的时候(小于int/2),可以使用node.val+MaxInt/2来做为标识位的同时,保持原有的数据信息。在执行完后进行数据还原。(这个解决办法的复杂度为O(n),同时能保护原有数据信息)

4,暴力法,不做标记,依次遍历每一个node.next的元素是不是之前曾经访问过的,两个for循环,复杂度O(n2)。

下述代码时间在处理一个非常大的list时时间超时

[code]/**
*Definitionforsingly-linkedlist.
*classListNode{
*intval;
*ListNodenext;
*ListNode(intx){
*val=x;
*next=null;
*}
*}
*/
publicclassSolution{
publicbooleanhasCycle(ListNodehead){
if(head==null){
returnfalse;
}
ListNodetemp;
ListNodehold=head;
while(hold!=null){
temp=head;
while(temp!=hold){
if(hold.next==null)
{
returnfalse;
}else{
while(temp!=hold){
if(hold.next==temp){
returntrue;
}
temp=temp.next;
}
if(hold.next==hold){
returntrue;
}
}
}
if(temp.next==hold){
returntrue;
}
hold=hold.next;
}
returnfalse;
}
}
[/code]

&&:本题的注意点:


测试用例,空list,单元素循环list,双元素循环list

循环list通过next访问是无限循环,所以需要设置好截至条件:返回值,断链等



(2)LinkedListCycle

(3)SingleNumber


Givenanarrayofintegers,everyelementappearstwiceexceptforone.Findthatsingleone.
Note:
Youralgorithmshouldhavealinearruntimecomplexity.Couldyouimplementitwithoutusingextramemory?
url:http://oj.leetcode.com/problems/single-number/


测试用例:单元素数组
本题的解法:
1.利用set不存储重复数据的特性,找出所有单个数据集合,然后2*sum(set)-sum(all)

这种解法的复杂度为O(n),遍历数组,每个数组元素查询,插入HashSet,查询和插入的复杂度为O(1),所以,总体复杂度为O(n)

需要额外的存储内存,HashSet



[code]publicclassSolution{
publicintsingleNumber(int[]A){
intallSum=0;
intnumSum=0;
Object[]numArr;
Setset=newHashSet();
for(inti=0;i<A.length;i++){
allSum+=A[i];
set.add(A[i]);
}
numArr=set.toArray();
for(inti=0;i<set.size();i++){
numSum+=Integer.parseInt(numArr[i].toString());
}
returnnumSum*2-allSum;
}
}
[/code]
2.使用HashMap,key为值,value为次数建立HashMap的复杂度为O(n),转成list,然后根据list遍历查询次数为1的项(可优化?)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐
章节导航