Leetcode brush question log 2.0

Table of contents

Foreword: 

1. The complement of a number

2. The maximum number of consecutive 1s 

3. The next larger element I 

4. Fibonacci numbers

5. Teemo attack

6.557. Reverse a word in a string III


Foreword: 

        Today, I will share with you the recent leetcode exercises, programming language: Python3. Not much nonsense, please read the question!

1. The complement of a number

        After inverting the binary representation of an integer (0 becomes 1, 1 becomes 0), and then converts it to a decimal representation, the complement of this integer can be obtained.

        For example, the binary representation of the integer 5 is "101", negated to get "010", and converted back to the decimal representation to get 2's complement. Now you are given an integer num, output its complement.

class Solution:
    def findComplement(self, num):
        b=bin(num)[2:]
        b=b.replace('0','a')
        b=b.replace('1','0')
        b=b.replace('a','1')
        return int(b,2)

Method: This question can be done like this, first convert the decimal number into a binary number string, then replace all the '0' in the binary number string with any character 'a', and then replace the Replace the '1' character with '0', and finally replace 'a' with '1' and it will be OK, thus completing the conversion of the binary number's complement, and then output the final converted decimal number through int(b,2) on the line

2. The maximum number of consecutive 1s 

Given a binary array  nums , calculate the largest continuous  1 number in it.

class Solution:
    def findMaxConsecutiveOnes(self, nums):
        li=[]
        count=0
        nums.append(8)
        for i in nums:
            if i!=1:
                li.append(count)
                count=0
            else:
                count+=1
        return max(li)

 Method:  first create a list to store li, and then enter the loop. When encountering 1, the count will be +1, if not, put the count into li, and finally we will find the list in li The number is the number of consecutive occurrences of 1, and in the end it is only necessary to return the largest one.

3. The next larger element I 

The next greater element of a number x in nums1 is the first element greater than x to the right of the corresponding position of x in nums2.

You are given two arrays nums1 and nums2 with no repeating elements, indexed from 0, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j satisfying nums1[i] == nums2[j], and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer to this query is -1.

Returns an array ans of length nums1.length as the answer such that ans[i] is the next greater element as above.

class Solution:
    def nextGreaterElement(self, nums1, nums2) :
        li = []
        for i in nums1:
            judge=False
            for j in range(nums2.index(i),len(nums2)):
                if nums2[j] > i:
                    judge=True
                    li.append(nums2[j])
                    break
            if not judge:
                li.append(-1)
        return li

Method: The method of this question is also relatively simple. First loop through nums1, get the position of the number of nums1 in nums2 at this time, and then loop through the number to the right of the position of nums2, if you encounter a number greater than this time Just add this number to the list li, if not found, add -1

 4. Fibonacci numbers

The sequence of Fibonacci numbers (usually denoted by F(n)) is called the Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. That is:

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), where n > 1
Now given n, compute F(n).

class Solution:
    def fib(self, n):
        if n==0:
            return 0
        a=1
        b=1
        if n==1 or n==2:
            return 1
        while n>2:
            c=a+b
            a=b
            b=c
            n-=1
        return b

Old topic, no more talk

5. Teemo attack

In the world of "League of Legends", there is a hero named "Teemo". His attack can make the enemy hero Ashe (Editor's Note: Ice Archer) into a poisoned state.

When Teemo attacks Ashe, Ashe is poisoned for exactly duration seconds.

Formally speaking, Teemo's attack at t means that Ashe is in a poisoned state during the time interval [t, t + duration - 1] (including t and t + duration - 1). If Teemo attacks again before the poison effect ends, the poison state timer will reset, and the poison effect will end in duration seconds after the new attack.

You are given a non-decreasing integer array timeSeries, where timeSeries[i] indicates that Teemo will attack Ashe at timeSeries[i] seconds, and an integer duration indicating the duration of the poisoning.

Returns the total number of seconds Ashe has been poisoned.

class Solution:
    def findPoisonedDuration(self, timeSeries, duration) :
        time=0
        for i in range(len(timeSeries)):
            if i<len(timeSeries)-1:
                if timeSeries[i+1]-timeSeries[i]<=duration:
                    time+=timeSeries[i+1]-timeSeries[i]
                else:
                    time+=duration
        return time+duration

 Method : Haha, everyone has played League of Legends, here we have to go in two steps, first divide the timeSeries into the last time period and the time period before the last time period, because the last time period is not involved in the comparison. Then loop through the time period before the last time period. When the interval between the next time point and the previous time point is less than or equal to duration, we add time to the difference between the two time points. At this time, Tim The time of the poisoning skill has also started to refresh; if the difference between the two time points is greater than the duration, just add the time to the duration, and finally remember to add the last time period after Teemo's poisoning skill refresh Time, just add duration to the experiment

6. 557. Reverse a word in a string III

Given a string  s , you need to reverse the order of the characters of each word in the string, while still preserving the spaces and the initial order of the words.

class Solution:
    def reverseWords(self, s) :
        li=s.split(' ')
        for i in range(len(li)):
            li[i]=li[i][::-1]
        return ' '.join(li)

 Method: First, we extract each word in this sentence, put it into a list, and then loop through the list, just reverse the order of each word in the list, and finally put the list between words Concatenate with spaces to return strings that meet the conditions

Well, the above is the content of today's exercises, see you in the next issue! ! 

 Share a wallpaper:

Guess you like

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