leetcode简单题(python)

简单题-python

1.两数之和

 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
# 1.
def twoSum(self, nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
#a = twoSum('self',[2,3,4,5,6],5)
#print(a)
class Solution:
    def twoSum(self, nums, target):
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i
        return []
#a =Solution
#b = a.twoSum(0,[3,3,4,5,6],7)
#print(b)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
       for i in nums:
           j = target - i
           start_index = nums.index(i)
           next_index = start_index + 1
           temp_nums = nums[next_index: ]
           if j in temp_nums:
               return (nums.index(i),next_index + temp_nums.index(j))
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict = {}
        for i in range(len(nums)):
            if target - nums[i] not in dict:
                dict[nums[i]] = i
            else:
                return [dict[target - nums[i]],i]

13.罗马数字转整数

class Solution:
    def romanToInt(self, s: str) -> int:    
        numeral_map = {"I": 1,"V": 5,"X": 10,"L": 50,"C": 100,"D": 500,"M": 1000}
        result = 0
        for i in range(len(s)):
            if i > 0 and numeral_map[s[i]] > numeral_map[s[i-1]]:
                result += numeral_map[s[i]] - 2 * numeral_map[s[i-1]]
            else:
                result += numeral_map[s[i]]
        return result
class Solution:
    def romanToInt(self, s: str) -> int:
        a = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        ans=0
        for i in range(len(s)):
            if i<len(s)-1 and a[s[i]]<a[s[i+1]]:
                ans-=a[s[i]]
            else:
                ans+=a[s[i]]
        return ans

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

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

给定数组 nums = [1,1,2], 
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 
你不需要考虑数组中超出新长度后面的元素。
class Solution:
    def removeDuplicates(self, nums):
        if not nums:
            return 0
        count = 0
        for i in range(len(nums)):
            if nums[count] != nums[i]:
                count += 1
                nums[count] = nums[i]
            print(i)
        return count + 1

389.找不同

给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
# ord() 函数是 chr() 函数(对于8位的ASCII字符串)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值
# map() 函数会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

# 比较每个字符在两个字符串中出现的次数
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        for i in t:
            if t.count(i)-s.count(i)==1:
                return i
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        return(chr(sum(map(ord,t))-sum(map(ord,s))))
        # ASII码对应的相减
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        for i in t:
            if i not in s or t.count(i) != s.count(i):
                return i
# 因为字符串 t 是由字符串 s 随机重排,然后在随机位置添加一个字母。
# 即对s和t中所有字符进行异或运算会剩下一字母也就是添加进去的那一个
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        # 利用字典
        # d = {}
        # for i in s:
        #     if i in d:
        #         d[i] += 1
        #     else:
        #         d[i] = 1        
        # for i in t:
        #     if i in d:
        #         if d[i] == 0:return i
        #         d[i] -= 1
        #    else:
        #         return i
        # 位运算
        ans = 0
        for i in s:
            ans ^= ord(i)
        for i in t:
             ans ^= ord(i)
        return chr(ans)

20.有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        looup = {"(":")","{":"}","[":"]"}
        for parenthese in s:
            if parenthese in looup:
                stack.append(parenthese)
            elif len(stack) == 0 or looup[stack.pop()] != parenthese:
                return False
        return len(stack) == 0

22.括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:

输入:n = 3
输出:[
       "((()))",
       "(()())",
       "(())()",
       "()(())",
       "()()()"
     ]
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n == 0:
            return []
        result = []
        self.helpler(n,n,'',result)
        return result
    def helpler(self,l,r,item,result):
        if r < l:
            return
        if l == 0 and r == 0:
            result.append(item)
        if l > 0:
            self.helpler(l-1,r,item+'(',result)
        if r > 0:
            self.helpler(l,r-1,item+')',result)

21.合并两个有序链表

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

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
# 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, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            cur = head =ListNode(0)
            while l1 and l2:
                if l1.val <= l2.val:
                    cur.next = l1
                    l1 = l1.next
                else:
                    cur.next = l2
                    l2 = l2.next
                cur = cur.next
            cur.next = l1 or l2
            return head.next

88.合并两个有序数组

给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出:[1,2,2,3,5,6]
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        while m > 0 and n > 0:
            if nums1[m-1] < nums2[n-1]:
                nums1[m-1+n] = nums2[n-1]
                n = n-1
            else:
                nums1[m-1+n], nums1[m-1] = nums1[m-1], nums1[m-1+n]
                m = m-1
        if m == 0 and n > 0:
            nums1[:n] = nums2[:n]

83.删除排序链表中的重复元素

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        cur = head
        while cur:
            runner = cur.next
            while runner and cur.val == runner.val:
                runner = runner.next
            cur.next = runner
            cur = cur.next
        return head

118.杨辉三角

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0:
            return []
        res = [[1]]
        while len(res) < numRows:
            newRow = [a+b for a,b in zip([0]+res[-1],res[-1]+[0])]
            res.append(newRow)
        return res

167.两数之和-输入有序数组

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 27 之和等于目标数 9 。因此 index1 = 1, index2 = 2
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        dct = {}
        for inx, i in enumerate(numbers):
            if i in dct:
                return [dct[i]+1, inx+1]
            dct[target-i] = inx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值