Python-----LeetCode brush question log 1.0 (basic 20 questions)

 Table of contents

Foreword:

1. The sum of two numbers

 2. Palindrome number

3. Longest Common Prefix

4. Valid Parentheses

5. Remove Duplicates in Sorted Array

6. Remove elements

 7. The length of the last word

8. Climb the stairs 

 9. Merge two sorted arrays

10. Yang Hui Triangle

 10. Verify palindrome string

11. The best time to buy and sell stocks 

 12. Most Elements

 13. The number of bit 1

14. Isomorphic Strings

15. There are repeated elements 

 16. Presence of repeating elements II

 17. Search insertion position

 18. Binary summation

19. Effective anagrams 

20. Missing Numbers


Foreword:

        Here I will share with you the questions I recently brushed on LeetCode, about 20 questions, programming language: Python. Hope you like it.

1. The sum of two numbers

The most direct way is to use a double-layer loop to directly find these two numbers and add them to the value of the target. If found, add these two numbers to the list li and return. The code is as follows:

class Solution(object):
    def twoSum(self, num, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        li=[]
        for i in range(len(num)):
            for j in range(i+1,len(num)):
                if target==num[i]+num[j]:
                    li.append(i)
                    li.append(j)
                    break
        return li

 2. Palindrome number

First convert this number into a string form, and then we can compare each character one by one in forward and reverse order, and return False if there is a difference, the code is as follows:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        x=str(x)
        for (i,j) in zip(range(len(x)),range(len(x)-1,-1,-1)):
            if x[i]!=x[j]:
                return False
        return True

3. Longest Common Prefix

 For this question, we can use the zip function to kill directly. First, decompress each list*, and then get multiple strings. Use the zip function to combine each group of strings with single characters, and then convert them into a set for viewing. The length of this set, if the length is 1, then it means that the single characters of this group are the same, the code is as follows:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        a = str()
        if strs:
            for i in zip(*strs):
                if len(set(i))==1:
                    a+=i[0]
                else:
                    return a
        
        return a

4. Valid Parentheses

 There is also a very simple way to this question, but it is hard to think of. This type of bracket matching problem will always have one of the three types of brackets {}, (), [] (if [), {] appear, it cannot be replaced), so we only need to put these three types of brackets Continuously replace with empty '', if the string becomes empty after the final replacement is completed, you can output True, anyway, output False, the code is as follows:

class Solution:
    def isValid(self, s):
        while '{}' in s or '()' in s or '[]' in s:
            s = s.replace('{}', '')
            s = s.replace('[]', '')
            s = s.replace('()', '')
        return s == ''

5. Remove Duplicates in Sorted Array

 We can go through the loop to compare the previous number with the next number, but there is a problem, that is, we don’t know who to compare the last number with, so we need to add a character 'a' as a reference. The c language is basically rotten, let’s look at the code below:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.append('a')
        k=0
        for i in range(len(nums)-1):
            if nums[i]!=nums[i+1]:
                nums[k]=nums[i]
                k+=1
        return k

6. Remove elements

 For this type of question, the approach is similar to the one above. Let’s look at the code:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        k=0
        for i in range(len(nums)):
            if nums[i]!=val:
                nums[k]=nums[i]
                k+=1
          
        return k

 7. The length of the last word

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        count=0
        k=0
        for i in range(len(s)-1,-1,-1):
            if k==1:
                k=0
            if s[i]==' ':
                k+=1
            else:
                count+=1
                k=2
            if k==3:
                break
        return count

  We can check directly in reverse order. When a space is encountered, k will be +1, and when k=1, k will return to 0, and so on until a non-space is encountered (this is the last word ) At this time, the value of k is 0, then count starts counting, and k is assigned a value of 2 until the space is encountered again, indicating that the last word count is completed, and the loop should end, at this time k=2+1=3 , end the loop

8. Climb the stairs 

In fact, I didn't have any idea about this question at first, but when I wrote a few numbers later, I found the pattern, that is, 1, 2, 3, 5, 8, 13...that is to say, the last one is equal to the previous one. The sum of the two is simply the same as the Fibonacci sequence. At this time, we can write code. 

 Essential method : You can imagine that when there are n steps in total, when you encounter the last two steps or the last step, you can directly step over it, well, did you step over before that? What about n-1 steps or n-2 steps? So we can assume that there are f(n) ways to boast n steps, so there will be f(n)=f(n-1)+f(n-2), isn’t this the Fibonacci sequence! ! !

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        a,b=1,1
        while n>1:
            a,b=b,a+b
            n-=1
        return b

 9. Merge two sorted arrays

 This question is very simple, just replace the last n items of num1 with num2, and then use the sort() function to sort directly. The code is as follows:

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: None Do not return anything, modify nums1 in-place instead.
        """
        if n!=0:
            nums1[-n:]=nums2
        nums1.sort()

10. Yang Hui Triangle

The law of Yanghui's triangle is as follows, so we need to generate numRows lists first, and add them directly according to the law of Yanghui's triangle. Look at the code:

 

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        li=[[1] for i in range(numRows)]
        for i in range(1,numRows):
            for j in range(1,i):
                if i>1:
                    li[i].append(li[i-1][j-1]+li[i-1][j])
            li[i].append(1)
        return li

 10. Verify palindrome string

 The idea is very straightforward, first convert to lowercase, then extract the numeric characters and alphabetic characters inside, and finally compare the forward and reverse order, the above code:

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        st=str()
        s=s.lower()
        for i in range(len(s)):
            if 'a'<=s[i]<='z' or '0'<=s[i]<='9':
                st+=s[i]
        if st==st[::-1]:
            return True
        else:
            return False

11. The best time to buy and sell stocks 

For this question, we can set the minimum value min and the maximum value of the difference max in turn. When encountering a situation that is greater than the current number min, we will assign a value. When the difference with the current value is greater than the current max value, we will assign a value. The code is as follows : 

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max=0
        min=prices[0]
        for p in prices[1:]:
            if min>p:
                min=p
                continue
            if max<p-min:
                max=p-min
        return max

 12. Most Elements

 The method is very simple. We first sort the array, and then output the median. The code is as follows:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[int(len(nums)/2)]

 13. The number of bit 1

 The method for this type of question is to convert the binary number into a decimal number first, and then convert the decimal number into a string form. It is very straightforward. Use the int() function to convert the binary number into a decimal number, and then use the bin() function to convert the binary number into a string. Decimal is converted to binary string form, the code is as follows:

class Solution:
    def hammingWeight(self, n: int) -> int:
        n=bin(int(n,2))
        return n.count('1')

14.  Isomorphic strings

 This question is also flexible to use the zip() function. First, it is necessary to judge whether the numbers of the two strings are the same after collection, and then use the zip function to combine the two strings together and then collect them. If they are collected If the number is the same as the original number, then it is an isomorphic string.

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(set(s))==len(set(t)):
            k=len(set(s))
            li=set((zip(s,t)))
            if len(li)==k:
                return True
            else:
                return False
        else:
            return False

15. There are repeated elements 

This type of question is also very simple. Using the deduplication function of the set, we directly compare the original length with the length after the collection. If they are the same, there will be no repeated elements, and vice versa. code show as below:

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums)==len(set(nums)):
            return False
        return True

 16. Presence of repeating elements II

 This problem can be solved by using the function of the dictionary. First, create an empty dictionary. We use the enumerate function to obtain the subscript and value of the number respectively, and then use the value as the key and the subscript as the value to add it to the dictionary. When encountering the same key, judge whether the difference between the current value and the value already in the dictionary is less than k, and return True if the condition is satisfied, and return False until the entire array is looped, and if it is not found, the code is as follows:

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        di={}
        for i,j in enumerate(nums):
            if j in di and i-di[j]<=k:
                return True
            else:
                di[j]=i
        return False

 17. Search insertion position

 Here it is necessary to consider whether the current target is greater than the maximum value or less than the minimum value of the array, and whether the array is empty. code show as below:

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            for i in range(len(nums)):
                if target<nums[i]:
                    nums.insert(i,target)
                    return i
                elif i==len(nums)-1 and i!=0:
                    return i+1
                elif nums[i]>target and len(nums)==1:
                    return i
                elif nums[i]<target and len(nums)==1:
                    return i+1

 18. Binary summation

 The idea is very simple, just convert the binary numbers to decimal and then add them, and then use the bin function to convert them into binary strings for output.

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

19. Effective anagrams 

 For this question, we can deal with the key-value pair properties of the dictionary (the character is the key and the quantity is the value), count the number of occurrences of the two string letters in turn, and finally judge whether the two dictionaries are equal. ,code show as below:

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        a={}
        b={}
        for i in s:
            if i in a:
                a[i]=a.get(i,0)+1
            else:
                a[i]=0
        for j in t:
            if j in b:
                b[j]=b.get(j,0)+1
            else:
                b[j]=0
        return a==b

20. Missing Numbers

 This group of numbers theoretically has n+1 numbers, but another number is not in it, so there are only n numbers, we only need to match them one by one through the loop, if there is a number that is not in this array, just returns this number.

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)+1):
            if i not in nums:
                return i

 Well, that's all for today, see you in the next issue! !

Share a wallpaper:

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/129497754