题16(中等):
思路:
双指针法,和15题差不多,就是要排除了,如果total<target则排除了更小的(left右移),如果total>target则排除了更大的(right左移)
python代码:
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() sum=nums[0]+nums[1]+nums[2] for i in range(len(nums)): if i>0 and nums[i]==nums[i-1]: continue left = i + 1 right = len(nums) - 1 while left < right: total=nums[i]+nums[left]+nums[right] if abs(target-total)<abs(target-sum): sum=total if total<target: left+=1 elif total>target: right-=1 else: return target return sum
题17(中等):
思路:
枚举列出来就好了,能过就行,虽然时间复杂度有点
python代码:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits=='':
return []
btn_json={
'1':'',
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz',
}
res_list=['']
for i in digits:
res=btn_json[i]
tmp_list=res_list
res_list=[n+j for n in tmp_list for j in res]
return res_list
题18(中等):
思路:
两数和,三数和,三数接近,这几题好玩吧,没尽兴就又来了一个4数和,一样的
python代码
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res_list=[]
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]:
continue
tmp_target=target-nums[i]
for j in range(i+1,len(nums)):
if j>i+1 and nums[j]==nums[j-1]:
continue
left=j+1
right=len(nums)-1
while left<right:
total=nums[left]+nums[right]+nums[j]
if total==tmp_target:
res_list.append([nums[i],nums[j],nums[left],nums[right]])
while left<right and nums[left]==nums[left+1]:
left+=1
while left<right and nums[right]==nums[right-1]:
right-=1
left+=1
right-=1
elif total<tmp_target:
left+=1
else:
right-=1
return res_list
题19(中等):
思路:
这个用c应该比较容易理解
python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
n_len=1
p=head
while 1:
if p.next!=None:
n_len+=1
p=p.next
else:
break
pos=n_len-n
p=head
if pos==0:
head=head.next
return head
for i in range(pos-1):
p=p.next
p.next=p.next.next
return head
题20(简单):
思路:
这个就是金典的栈的运用啊,我之前还有一个文章是表达式的转换来着
python代码:
class Solution:
def isValid(self, s: str) -> bool:
s_stack=[]
for i in s:
if i=='(' or i=='{' or i=='[':
s_stack.append(i)
elif i==')':
if len(s_stack)!=0 and s_stack[-1]=='(':
s_stack.pop()
else:
return False
elif i == '}':
if len(s_stack)!=0 and s_stack[-1] == '{':
s_stack.pop()
else:
return False
elif i == ']':
if len(s_stack)!=0 and s_stack[-1] == '[':
s_stack.pop()
else:
return False
if len(s_stack)==0:
return True
else:
return False
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 力扣16~20题
发表评论 取消回复