leetcode 练习(二)

本文深入解析了LeetCode上的经典算法题目,包括二分查找、分治策略、链表操作、哈希表应用、字符串比较、栈与队列实现等。通过具体的Python代码示例,详细介绍了每种算法的实现过程及核心思想。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 69 二分

 https://leetcode.com/problems/sqrtx/description/

class Solution(object):
    def mySqrt(self, x):
        if x==1 or x==0:
            return x
        else:
            left=0
            right=x
            while left<right:
                temp=(left+right)/2
                if int(temp)**2<=x and int((temp+1))**2>=x:                
                    if int((temp+1))**2==x:
                        temp=int((temp+1))
                    return(int(temp))
                    break        
                elif int(temp)**2<x and int(temp+1)**2<x:
                    left=temp             
                else:
                    right=temp

 

leetcode 241 分治

https://leetcode.com/problems/different-ways-to-add-parentheses/description/

 

class Solution(object):
    def diffWaysToCompute(self, input):
        """
        :type input: str
        :rtype: List[int]
        """
        if input.isdigit():
            return [int(input)]
        res=[]
        n=len(input)
        for i in range(n):
            if input[i] in '+-*':
                res1 = self.diffWaysToCompute(input[:i])
                res2 = self.diffWaysToCompute(input[i+1:])
                for j in res1:
                    for k in res2:
                        res.append(self.group(j,k,input[i]))
        return res
        
        
    def group(self,a,b,str):
        if str=='+':
            return a+b
        elif str=='-':
            return a-b
        else:
            return a*b

 leetcode 160 链表

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA is None or headB is None:
            return None
        pa=headA
        pb=headB
        
        while pa is not pb:
            pa=headB if pa is None else pa.next
            pb=headA if pb is None else pb.next
        return pa

leetcode 1 哈希

 https://leetcode.com/problems/two-sum/description/

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup={}
        for i in range(len(nums)):
            complement=target-nums[i]
            if lookup.get(complement)!=None:
                return[i,lookup.get(complement)]
            lookup[nums[i]]=i
        return []

leetcode 242 字符串

 https://leetcode.com/problems/valid-anagram/description/

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic1,dic2=[0]*26,[0]*26
        for i in s :
            dic1[ord(i)-ord('a')]+=1
        for i in t:
            dic2[ord(i)-ord('a')]+=1
        return dic1==dic2

leetcode 232 栈和队列

 https://leetcode.com/problems/implement-queue-using-stacks/description

class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack1=[]
        self.stack2=[]

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: None
        """
        self.stack1.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if len(self.stack2)!=0:
            self.stack2.pop()
        else:
            while len(self.stack1)!=0:
                self.stack2.append(self.stack1.pop())
            self.stack2.pop()
    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        if len(self.stack2)!=0:
            return self.stack2[-1]
        else:
            while len(self.stack1)!=0:
                self.stack2.append(self.stack1.pop())
            return self.stack2[-1]
        

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        if len(self.stack1) ==0 and len(self.stack2)==0:
            return True
        else:
            return False


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值