leetcode简单题1~50

这篇博客汇总了解决LeetCode中1~50号简单题目的不同解法,涉及问题包括两数之和、整数反转、回文数、罗马数字转整数等。博主分享了自己的解决方案(yueyue's solution)以及高手的解法(Dalao's solution),并提供了思考点,比如哈希表的运用、特殊情况处理和时间复杂度优化等。
摘要由CSDN通过智能技术生成

1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

  1. yueyue’s solution
class Solution:
    def twoSum(self, nums, target):
        n=len(nums)
        for i  in range(n):
            for j in range(i+1,n):
                if nums[i]+nums[j]==target:
                    return i,j
  1. Dalao’s solution
def twoSum(nums, target):
    hashmap={
   }
    for i,num in enumerate(nums):
        if hashmap.get(target - num) is not None:
            return [i,hashmap.get(target - num)]
        hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况

thinking:该学一学哈希表,《算法图解》第五章待看(后续补充)

7. 整数反转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [ − 2 31 , 2 31 − 1 ] [−2^{31}, 2^{31} − 1] [231,2311]。请根据这个假设,如果反转后整数溢出那么就返回 0。

  1. yueyue’s solution
class Solution:
    def reverse(self,x):
        sign=1
        if x<0:
            sign=-1
            x=abs(x)
        num=int(''.join(list(str(x))[::-1]))
        if num<=2**31:
            return num*sign
        else:
            return 0
  1. Dalao’s solution
class Solution:
    def reverse(self,x):
        y, res = abs(x), 0
        # 则其数值范围为 [−2^31,  2^31 − 1]
        boundry = ((1<<31) -1)//10 
        print(boundry)
        ones= ((1<<31) -1)%10 if x>0 else  (1<<31)%10
        while y != 0:
            if (res > boundry) or ((y>ones)and(res == boundry)):
                return 0
            res = res*10 +y%10
            y //=10
        return res if x >0 else -res

thinking:要先判断储不储存得下啊 !!切片可能不符合题意啊……

9. 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

  1. yueyue’s solution
class Solution:
    def isPalindrome(self, x) :
        x=str(x)
        y=x[::-1]
        return x==y
  1. Dalao’s solution
class Solution:
    def isPalindrome(self, x) :
        if x<0:
            return False
        else:
            res,y=0,x
            while y!=0:
                res=res*10+y%10
                y//=10
            return res==x

thinking:特殊情况,如是负数则一定不是回文数,直接返回 false

13. 罗马数字转整数

  1. yueyue’s solution=Dalao’s
class Solution:
    def romanToInt(self, s) :
        n=0
        R_dict = {
   'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}        
        for i in range(len(s)):
            if i!=len(s)-1 and R_dict[s[i]] <R_dict[s[i+1]]:
                n-=R_dict[s[i]]
            else:
                n+=R_dict[s[i]]
        return n

14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

  1. yueyue’s solution
class Solution:
    def longestCommonPrefix(self,strs):
        same_pre=""
        index=0
        if ""in strs or strs==[]:
            return same_pre
        elif len(strs)==1:
            return strs[0]
        else:
            while index<len(strs[0]):
                same_pre+=strs[0][index]
                for s in strs[1:]:
                    if index<len(s) and s[index]!=same_pre[index]:
                        return same_pre[:-1]
                    elif index==len(s):
                        return same_pre[:-1]
                index+=1
            return same_pre

2.yueyue’s improvement

class Solution:
    def longestCommonPrefix(self,strs):
        if  strs==[]:
            return ""
        for i in range(len(strs[0]),0,-1):
            tem=strs[0][:i]
            for s in strs[1:]:
                if s[:i]!=tem:
                    break   
            else:
                return tem
        return  ""

20. 有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

yueyue’s solution

class Solution:
    def isValid(self, s: str) -> bool:
        pare_dict={
   '(':')','{':'}','[':']'}
        right=[]
        for i in s:
            if i in pare_dict:
                right.append(pare_dict.get(i))
            elif right:
                if i==right.pop():
                    continue
                else:
                    return False
            else:
                return False
        if right==[]:
            return True
        else:
            return False
  1. Dalao’s solution
class Solution:
    def isValid(self, s: str) -> bool:
        pare_dict={
   '(':')','{':'}','[':']'}
        right=[]
        for i in s:
            if i in pare_dict:
                right.append(pare_dict.get(i))
            elif right:
                if i==right.pop():
                    continue
                else:
                    return False
            else:
                return False
        return not right

21. 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

  1. yueyue’s solution
# 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:

        cur1=l1
        cur2=l2
        new=ListNode()
        cur3=new
        while cur1!=None and cur2!=None:
            if cur1.val<=cur2.val:
                cur3.next=ListNode(cur1.val) 
                cur1=cur1.next  
            elif cur1.val>cur2.val:
                cur3.next=ListNode(cur2.val) 
                cur2=cur2.next 
            cur3=cur3.next
        if cur1!=None: cur3.next=cur1
        if cur2!=None: cur3.next=cur2
        return new.next
  1. Dalao’s solution
    递归用的太妙了
# 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==None:
            return l2
        if l2==None:
            return l1
        
        if l1.val<=l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2

26. 删除排序数组中的重复项

给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

  1. yueyue’s solution
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
       
        for i in nums:
            n_count=nums.count(i)
            if n_count>1:
                for j in range(n_count-1):
                    nums.remove(i)
        return len(nums)
  1. yueyue’s impovement
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:

        y=1
        for i in range(1,len(nums)):
            if nums[i-1]<nums[i]:
                nums[y]=nums[i]
                y+=1
        return y
  1. Dalao’s solution
    双指针
def removeDuplicates(nums):
    i=0
    j=1   
    while j<len(nums):
        if nums[j]>nums[i]:
            i+=1            
            nums[i]=nums[j]       
        j+=1

    return i+1

27. 移除元素

给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

  1. yueyue’s solution
class Solution:
    def removeElement(self, nums, val):
        i=0
        for j in range(len(nums)<
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值