程序地带

leetcode刷题4


在这里插入图片描述 我的思路:1.暴力解题,三重for循环 2.双指针法,将复杂度降低到O(n2)


class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
closet_num=100000
for k in range(len(nums)):
i,j=k+1,len(nums)-1
while(i<j):
if abs(nums[k]+nums[i]+nums[j]-target)<abs(closet_num-target):
closet_num=nums[k]+nums[i]+nums[j]
if nums[k]+nums[i]+nums[j]>target:
j-=1
elif nums[k]+nums[i]+nums[j]<target:
i+=1
elif nums[k]+nums[i]+nums[j]==target:
return target
return closet_num
#超级笨方法
'''closet_num=1000
for x in range(len(nums)-2):
for y in range(x+1,len(nums)-1):
for z in range(y+1,len(nums)):
if abs(nums[x]+nums[y]+nums[z]-target)<abs(closet_num-target):
closet_num=nums[x]+nums[y]+nums[z]
return closet_num'''

在这里插入图片描述 我的思路:用栈,左边的括号进栈,遇见右括号出栈,最后判断栈是否为空


class Solution:
def isValid(self, s: str) -> bool:
'''if len(s)%2 is not 0 or len(s)==0:
return False
dic={'{':'}','[':']','(':')'}
stack=[]
for i in s:
if i in dic:
stack.append(i)
elif i not in dic and len(stack)!=0 and dic[stack[-1]]==i:
stack.pop()
else:
return False
return len(stack)==0'''
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''

在这里插入图片描述 我的思路;1.遍历节点,储存所有的值,排序后建立链表 2.通过指针的改变


# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if(l1 is None and l2 is not None):
return l2
if(l2 is None and l1 is not None):
return l1
if(l2 is None and l2 is None):
return None
'''sort_list=[]
while(l1 is not None):
sort_list.append(l1.val)
l1=l1.next
while(l2 is not None):
sort_list.append(l2.val)
l2=l2.next
sort_list.sort()
head=ListNode(sort_list[0])
tail=head
for element in sort_list[1:]:
node=ListNode(element)
tail.next=node
tail=node
return head'''
head=ListNode(min(l1.val,l2.val))
tail=head
while(l1 is not None and l2 is not None):
if l1.val<=l2.val:
tail.next=l1
l1=l1.next
tail=tail.next
elif l1.val>l2.val:
tail.next=l2
l2=l2.next
tail=tail.next
if l1 is None:
tail.next=l2
if l2 is None:
tail.next=l1
return head.next

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_47718334/article/details/112689104

随机推荐

Comparable排序

对成绩信息进行排名,按成绩降序进行顺序输出,如果出现成绩相同则先输出学号小的信息。importjava.util.ArrayList;importjava.util.Col...

中二咸鱼王 阅读(131)

uniapp

constpages=getCurrentPages();//获取页面栈constbeforePage=pages[pages.length-2];//前一个页面beforePage....

float-left 阅读(946)