leetcode 简单题目(python)1-20

1. Two Sum(e-1)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution(object):
    def twoSum(self, nums, target):
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if i!=j and nums[i]+nums[j]==target:
                    print(i,j)

7. Reverse Integer(e-2)

Given a 32-bit signed integer, reverse digits of an integer.

class Solution(object):
    def reverse(self, x):
        if '-' not in str(x):
            x=[int(i) for i in list(str(x))]
            x=x[::-1]
        else:
            x=abs(x)
            x=[int(i) for i in list(str(x))]
            x=x[::-1]
            x=-x
            

9. Palindrome Number(e-3)

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
class Solution(object):
    def isPalindrome(self, x):
        if x>0:
            a=[int(i) for i in list(str(x))]
            x=[int (i) for i in list(str(x))]
            a=a[::-1]
            if a==x:
                return True
            else:
                return False
        else:
            x=abs(x)
            a=[int(i) for i in list(str(x))]
            x=[int (i) for i in list(str(x))]
            a=a[::-1]
            if a==x:
                return True
            else:
                return False

13. Roman to Integer(e-4)

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {"I":1, "V": 5, "X":10,"L":50,"C":100, "D":500, "M":1000}
        ans = 0
        for i in xrange(0, len(s) - 1):
            c = s[i]
            cafter = s[i + 1]
            if d[c] < d[cafter]:
                ans -= d[c]
            else:
                ans += d[c]
        ans += d[s[-1]]
        return ans

14. Longest Common Prefix(e-5)

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""
        if len(strs) == 1:
            return str[0]
        minl=min([len(x) for x in strs])
        end=0
        while end < minl:
            for i in range(1,len(strs)):
                if strs[i][end]!= strs[i-1][end]:
                    return strs[0][:end]
            end += 1
        return strs[0][:end]

20. Valid Parentheses(e-6)

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

class Solution(object):
    def isValid(self, s):
       
        stack = []
        d = ["()", "[]", "{}"]
        for i in range(0, len(s)):
            stack.append(s[i])
            if len(stack) >= 2 and stack[-2]+stack[-1] in d:
                stack.pop()
                stack.pop()
        return len(stack) == 0

21. Merge Two Sorted Lists(e-7)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        head = dummy = ListNode(-1)
        while l1 and l2:
            if l1.val<l2.val:
                head.next=l1
                l1=l1.next
            else:
                head.next=l2
                l2=l2.next
            head=head.next
        if l1:
            head.next=l1
        if l2:
            head.next=l2
        return dummy.next

26. Remove Duplicates from Sorted Array(e-8)

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return len(nums)
        slow = 0
        for i in xrange(1, len(nums)):
            if nums[i] != nums[slow]:
                slow += 1
                nums[slow] = nums[i]
        return slow + 1

27. Remove Element(e-9)

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

class Solution(object):
    def removeElement(self, nums, val):
        
        slow = -1
        for i in xrange(0, len(nums)):
            if nums[i] != val:
                slow += 1
                nums[slow] = nums[i]
        return slow + 1

28. Implement strStr(e-10)

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

class Solution:
    def strStr(self, haystack, needle):
        return haystack.find(needle)
    
            
        

35. Search Insert Position(e-11)

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        lo = 0
        hi = len(nums)
        while lo < hi:
            mid = lo + (hi - lo) / 2
            if nums[mid] > target:
                hi = mid
            elif nums[mid] < target:
                lo = mid + 1
            else:
                return mid
        return lo

38. Count and Say(e-12)-------没看懂,以后补

The count-and-say sequence is the sequence of integers with the first five terms as following:

53. Maximum Subarray(e-13)

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

class Solution:
    def maxSubArray(self, nums):
        if len(nums) == 0:
            return 0
        presums=maxsums=nums[0]
        for i in range(1,len(nums)):
            presums=max(presums+nums[i], nums[i])
            maxsums=max(presums, maxsums)
        return maxsums

58. Length of Last Word(e-14)

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        while len(s):
            s=s.split()
            if len(s) > 0:
                return len(s[-1])
            return 0

66. Plus One(e-15)

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[-1]=digits[-1]+1
        print(digits)

67. Add Binary(e-16)

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return bin(int(a, 2) + int(b, 2))[2:]

69. Sqrt(x)(e-17)

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        lo = 0
        hi = x
        while lo <= hi:
            mid = (hi + lo) / 2
            v = mid * mid
            if v < x:
                lo = mid + 1
            elif v > x:
                hi = mid - 1
            else:
                return mid
        return hi

70. Climbing Stairs(e-18)

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

class Solution(object):
    def climbStairs(self, n):
        if n<=1:
            return 1
        pre=1
        ppre=1
        for i in range(2,n+1):
            tmp=pre
            pre=ppre+pre
            ppre=tmp
        return pre
            

83. Remove Duplicates from Sorted List(e-19)

Given a sorted linked list, delete all duplicates such that each element appear only once.

class ListNode:
    def __init__(self,x):
        self.val=x
        self.next=None
        
class Solution(object):
    def deleteDuplicates(self,head):
        dummy=ListNode(None)
        dummy.next=head
        p=dummy
        while p and p.next:
            if p.val == p.next.val:
                p.next=p.next.next
            else:
                p=p.next
        return dummy.next
    
                

88. Merge Sorted Array(e-20)

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
    class Solution(object):
        def merge(self, nums1, m, nums2, n):
            """
            :type nums1: List[int]
            :type m: int
            :type nums2: List[int]
            :type n: int
            :rtype: void Do not return anything, modify nums1 in-place instead.
            """
            end = m + n - 1
            m -= 1
            n -= 1
            while end >= 0 and m >= 0 and n >= 0:
                if nums1[m] > nums2[n]:
                    nums1[end] = nums1[m]
                    m -= 1
                else:
                    nums1[end] = nums2[n]
                    n -= 1
                end -= 1
                    
            while n >= 0:
                nums1[end] = nums2[n]
                end -= 1
                n -= 1

     

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: LeetCode是一个优秀的在线编程平台,提供了丰富的算法和数据结构题目供程序员练习。其中的简单题大多可以用Python语言编写,下面为您提供几个常见题目Python版本答案。 1. 两数之和(Two Sum) 题目描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 Python版本答案: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if target - x in d: return [d[target - x], i] d[x] = i 2. 反转字符串(Reverse String) 题目描述:编写一个函数,其作用是将输入的字符串反转过来。 Python版本答案: class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 3. 回文数字(Palindrome Number) 题目描述:判断一个整数是否是回文数,例如:121是回文数,-121不是回文数。 Python版本答案: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False if x == 0: return True str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True 以上只是这几个简单题目Python版本答案,实际上LeetCode上还有很多其他编程语言编写的优秀答案,需要程序员们自己去探索和实践。 ### 回答2: Leetcode是一个流行的在线编程题库,提供了许多关于算法和数据结构的题目,难度从简单到困难不等。Python是一种易学易用的编程语言,备受程序员欢迎。因此,许多程序员使用Python来解决Leetcode的编程问题。下面我将提供一些Python版本的Leetcode简单题的答案。 1. 两数之和 题目描述:给定一个整数数组和一个目标值,在数组中找到两个数之和等于目标值。 解题思路:使用哈希表来存储数组中每个元素的值和索引,然后遍历每个元素时,查找目标值减去当前元素的值是否在哈希表中,如果存在,返回两个值的索引。 Python代码: def twoSum(nums, target): hash_table = {} for i, num in enumerate(nums): complement = target - num if complement in hash_table: return hash_table[complement], i hash_table[num] = i nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target)) # Output: (0, 1) 2. 路径总和 题目描述:给定一棵二叉树和一个目标值,判断是否存在从根节点到叶节点的路径,使得路径上所有节点的值相加等于目标值。 解题思路:遍历二叉树的所有路径,判断路径上所有节点的值相加是否等于目标值。 Python代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(root, sum): if not root: return False if not root.left and not root.right and root.val == sum: return True return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) sum = 22 print(hasPathSum(root, sum)) # Output: True 3. 最大子序和 题目描述:给定一个整数数组,找到一个具有最大和的子数组,返回该子数组的和。 解题思路:使用动态规划,定义状态dp[i]表示以第i个数结尾的最大子数组和,则状态转移方程为dp[i] = max(dp[i-1] + nums[i], nums[i])。 Python代码: def maxSubArray(nums): if not nums: return 0 n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp) nums = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(nums)) # Output: 6 总结:以上是三个Python版本的Leetcode简单题的答案,它们涉及到哈希表、二叉树、动态规划等算法和数据结构。这些题目既考验了程序员的基本功,又是训练算法思维的好工具。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值