穿针引线以此类推ListNode*reverseBetween(ListNode*head,intleft,intright){ListNode*dummyNode=newListNode(-1);dummyNode->next=head;ListNode*pre=dummyNode;for(inti=0;i<left-1;++i){pre=pre->next;}ListNode*cur=pre->next;ListNode*next;for(inti=0;i<right-left;++i){next=cur->next;cur->next=next->next;//从这开始next->next=pre->next;pre->next=next;}returndummyNode->next;}
funcaddTwoNumbers(l1*ListNode,l2*ListNode)*ListNode{ifl1==nil||l2==nil{returnnil}head:=&ListNode{Val:0,Next:nil}current:=headcarry:=0forl1!=nil||l2!=nil{varx,yintifl1==nil{x=0}else{x=l1.Val}ifl2==nil{y=0}else{y=l2.Val}current.Next=&ListNode{Val:(x+y+carry)%10,Next:nil}current=current.Nextcarry=(x+y+carry)/10ifl1!=nil{l1=l1.Next}ifl2!=nil{l2=l2.Next}}ifcarry>0{current.Next=&ListNode{Val:carry,Next:nil}}returnhead.Next}总结carry代表进位,一位一位加即可,若其中一条链到底,均设置为0,直到两条都到底,结束,最后跳出循环再判断最后一位是否还有进位,有进位再添加一个节点记录。
packageleetcode//hash算法,visited采用hashmap存储,每遍历一个数,就检查target-num的差是否在hashmap存在了,存在则返回,不存在则记录,继续遍历functwoSum(nums[]int,targetint)[]int{varvisited=make(map[int]int,len(nums))fori,num:=rangenums{sub:=target-numifj,ok:=visited[sub];ok{return[]int{i,j}}else{visited[num]=i}}returnnil}//穷搜,固定一个数num,搜索剩余数+num?=targetfunctwoSum2(nums[]int,targetint)[]int{fori,num:=rangenums{forj:=i+1;j<len(nums);j++{ifnum+nums[j]==target{return[]int{i,j}}}}returnnil}