Power button problem

Power button 12: integer reversal

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

输入:123
输出:321

Example 2:

输入:-123
输出:-321

Example 3:

输入:120
输出:21

note:

Suppose we have an environment can only store a 32-bit signed integer, then the value range [-2 ^ 31, 2 ^ 31--1] Please Under this assumption, if 0 is returned inverted integer overflow.

Outline of Solution: integer into a string, index-reversed with stitching symbol characters, negative. Since the predetermined range of values, conditional add.

Code:

class Solution:
    def reverse(self,x:int)->int:
        x = str(x)
        if x[0]== '-':      #判断带-号的数字
            x = int('-'+x[:0:-1])  #保留符号,数字反转
        else:
            x = int(x[::-1])     
        if x < -2147483648 or x >2147483648:
            return 0
        else:
            return x       # x为以上反转后的数字,而非原来的数字

Power button 13: two numbers and the ordered set of input II-

Given an ordered array is sorted in ascending order according to find the two numbers such that their sum is equal to the sum of the target number.

Function should return the two index values ​​index2 and index1, index2 wherein index1 must be less than

Description:

  • Return values ​​of the index (index1, index2 and) is not zero.
  • You can assume that each input corresponding to only the only answer, but you can not reuse the same elements.

Example:

输入:numbers = [2,7,11,15],target = 9
输出:[1,2]
解释:2与7之和等于目标数9.因此index1=1,index2=2.

Method 1: the double pointer

  • from left to right sweep left hand, right hand from right to left scan
  • If numbers [left] + numbers [right] == ​​target instructions and the output matching left + 1 right + 1 (subscript 1 from the start, so plus 1)
  • If numbers [left] + numbers [right] <target instructions and the need to increase the number of two, left to right pointers (array in ascending order)
  • If the numbers + numbers [right]> target DESCRIPTION [left] and the need to reduce the number of two on the right hand to the left (in ascending order array)

Code:

class Solution(object):
    def teoSum(self,numbers,target):
        left = 0
        right =len(numbers)-1
        while left < right:
            if numbers[left]+numbers[right] == target:
                return [left+1,right+1]
            elif numbers[left]+numbers[right] < target:
                left += 1
            else:
                right -= 1
    

Method two: requires additional space (dictionary) has been stored swept element values ​​and the subscript

  • Every look in the dictionary there is no target-numbers [i]
    • If so, the output of the i + 1 corresponding to the dictionary and corresponding to the value of the key
    • If not, the numbers [i] was added dictionary
class Solution(object):
    def twoSum(self,numbers,target):       
        dict_l = {}  # 存放的k:v,数组:下标
        for i in range(len(numbers)):   
            n = target-numbers[i]
            if n in dict_l:
                return [dict_l[n],i+1]
            dict_l[numbers[i]] = i+1

Power button 14: a rotating string

Given two strings A and B.

A rotation of the operation is to A leftmost character to move to the far right. For example, if A = 'abcde', after the movement is a result of 'bcdea'. If after several rotating operation, A can become B, then return True.

Example:

示例1:
输入:A = 'abcde',B = 'cdeab'
输出:true

Example 2:

输入:A = 'abcde',B = 'abced'
输出:false

Outline of Solution: After rotating the character, the same length, due to the movement in the final surface, therefore, a perfect string comprising B 2A

class Solution:
    def rotateString(self,A:str,B:str)->bool:
        return len(A) == len(B) and B in A+A  

Power button 15: the last stone of weight

A pile of stones, the weight of each stone are positive integers, each round, to choose the most important two stones, and then pulverized with them. Suppose stone weights of x and y, and x <= y. Then crushed possible results are as follows:

  • If x = y, then two stones will be completely crushed.
  • If x != y, then the weight will be completely crushed stone x, and y weight of the weight of the stone new yx.

Finally, he will only rest a stone. Returns the weight of this stone. If there is no stone left over, it returns 0.

Outline of Solution: stone now descending order, if the length is greater than a stone, has been pulverized cool.

class Solution:
    def lastStoneWeight(self,stones:List[int])->int:
        stones.sort(reverse=true)  #将列表从小到大排列
        while(len(stones)>1):
            if stones[0] == stones[1]:  #x == y
                stones.pop(0)           #删除y
                stones.pop(0)           #删除x
            else:
                stones[0]=stones[0]-stones[1]  #最大的石头重量为y-x
                stones.pop(1)                   #删除x
                stones.sort(reverse=True)       #将删除之后的列表进行排序
        if stones:                           #列表存在
            return stones[0]                 #返回最后的石头重量
        return 0                             #否则返回0

Power button 16: Spot The Difference

Given two strings s and t, they contain only lowercase letters. String rearrangement t s by the random string, and add a letter at random locations. Find the letters are added in t.

Example:

s = "abcd"
t = "abcde"

输入:e

解释:
'e'是那个被添加的字母

Problem-solving ideas: first string into a list, the letters s taken out is compared with the letters taken out of t, the same letter s is deleted, only a last element in the t

class Solution:
    def findTheDifference(self,s:str,t:str)->str:
        list_s = list(s)   # 将s字符串转化为列表
        list_t = list(t)   # 将t字符串转化为列表
        
        for i in range(len(list_s)): # 循环len(list_s)
            for j in range(len(list_t)):
                if list_s[i] == lsit_t[j]: # 如果s列表中的字母,在t列表中
                    del list_t[j]          #删除
                    break                 
        result = ''.join(list_t)
        return result

Power button 17: a plus

Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

Up to first place in the digital storage array, each element of the array stores only one number.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:

输入:[1,2,3]
输出:[1,2,4]
解释:输入数组表示数字123。

Example 2:

输入:[4,3,2,1]
输出:[4,3,2,1]
  • Traversal digits, each judge whether 9, if not then +1and returned, otherwise this position 0;
  • For digitsthere are all 9cases, the need to expand the list, and the first position 1.
class Solution:
    def plusOne(self,digits:[int])->[int]:
        for i in range([len(digits)-1,-1,-1]):  # 先判断个位的,再判断十位。
            if digits[i] != 9:   # 位数字是否为9
                digits[i] += 1   # 不是10,位数字加1
                return digits
            digits[i] = 0        # 位数字全是9,置零
        digits[0] = 1            # 首位置1
        digits.append(0)         # 末尾追加0
        return digits

Power button 18: the first string a unique character

Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.

Case:

s = "leetcode"
返回0.

s = "loveleetcode"
返回2.
class Solution:
    def firstUniqChar(self,s:str)->int:
        for i in range(len(s)):
            if s.find(s[i]) == s.rfind(s[i])  # 左边找字母的索引与右边字母索引相同
            return i
        return -1
find是从左往右搜索,rfind是从右往左搜索,都是返回第一个匹配的下标。如果两者一致,证明这个就是唯一值。

python 100 questions: one question multiplication table

9 * 9 outputs the multiplication tables

Xu procedure: Branches column consideration, a total of 9 rows 9 columns, row control I, j the control column.

for i in range(1,10):  # 循环9次,
    for j in range(1,i+1): #对应1,到i+1
        print(f'{i}*{j}={i*j}'',end=' ')
    print()    #控制换行   

Turn dictionaries list

List into dictionary

i = ['a','b']
l = [1,2]
print(dict(zip(i,l)))  #zip()函数,第一个值转化为keys值,第二个为values

{'a': 1, 'b': 2}

Number combinations

There are four numbers: 1, 2, how many other with no repeat can be composed of triple-digit figures is the number??

Program Analysis: traverse all possible, remove the duplicate.

total = 0
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if ((i!=j)and(j!=k)and(k!=i)):  #重复的全部去掉
                print(i,j,k)
                total += 1
print(total)

1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
24

Easy way: you can use itertools of permutations.

import itertools
sum2 = 0
a = [1,2,3,4]
for i in itertools.permutations(a,3):
    print(i)
    sum2 += 1
    print(sum2)
itertools库 combinations()和permutations  组合和排列选项的方法
import itertools
s = [1,2,3]
#组合
#组合
print(list(itertools.combinations('abc',2)))
#排列
print(list(itertools.permutations(s,3)))

[('a', 'b'), ('a', 'c'), ('b', 'c')]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Examples 009: second pause output

Program analysis: second pause output

import time
for i in range(4):
    print(str(int(time.time()))[-2:])  #time.time(),从1970开始的秒数
    time.sleep(1)       #睡眠一秒

Examples 045: sum

Title: statistics and 1-100 of

res = 0
for i in range(1,101):
    res += i
print(res)    

Exchange position

Input array, the first maximum switching element with minimal exchange the last element, the array output.

li = [3,2,5,7,8,1,5]

li[-1],li[li.index(min(li))] = li[li.index(min(li))],li[-1]

m = li[0]
ind = li[ind]
li[ind] = m

print(li)

center () centered

Description: Returns the length of a width, on both sides with FillChar (single character) filled string, the string str centrally, on both sides filled with fillchar. If the length of the string is greater than the width, directly returns the string str

Syntax: str.center (width, "fillchar") -> str Returns string Note: can not be omitted quotes

print('i love python'.center(40,"*"))

*************i love python**************

print('i love python'.center(1,"*"))

i love python

print('i love python'.center(39,"#"))

#############i love python#############

ljust (), rjust () left justified, right justified

print('i love python'.ljust(40,'*'))

i love python***************************

print('i love python'.rjust(40,'*'))

***************************i love python

Power button 728: Self divisor

Since the divisor is the number of each can be divisible by the number of bits it contains.

For example: 128 is a self-divisor, because 128 % 1 == 0, 128 % 2 ==0, 128 % 8 ==0.

Also, since the divisor not contain zero.

A given number on the boundary, outputs a list of all the elements of the list is the divisor from the inner boundary (inclusively).

Example 1:

输入:
上边界left = 1,下边界right = 22
输出:[1,2,3,4,5,6,7,8,9,11,12,15,22]

Note: The boundaries satisfy each parameter input1<= left <=right<=10000。

Problem-solving ideas: the circulation between the digital and lower boundary removed, each digital conversion cycle the fetched character is a string, and if the character contains the remainder is not 0 and is not added to the list 0.

class Solution:
    def selfBividingNumbers(self,left:int,right:int)->List[int]:
        res = []
        for i in range(left,right+1):
            for j in str(i):
                if j == '0' or i %int(j) !=0:
                    break  # 中断一个数的取字符循环
            else: #for循环有break,则不会添加到列表中
                res.append(i)
        return res        

Stay button: Nim game

You and your friends, two people to play with Nim game: There is a push stones on the table, every time you turn removed 1-3 blocks

stone. Removed the last stone of the person is the winner. As you just get.

You are all smart people, every step is the optimal solution. Write a function to determine whether you can win the game, given the number of stones.

Example:

输入:4
输出:false
解释:如果堆中有4块石头,那么你永远不会赢得比赛;因为无论你拿走1块、2块、还是3块石头,最后一块石头总是会被你的朋友拿走。

Analysis: When 1,2,3 n =, you win the game

When n = 4, no matter how many you take, you will not win the game

n = 5, you take one, you win, the remaining 4

When n = 6, you get two, you win, the remaining 4

When n = 7, 3 you take, you win, the remaining 4

n = 8, you get the number, you will not win,

0900 n =, you get one, you win, the remaining eight,

The analysis found that, when n% 4 == 0, no matter how many I get, I do not win

class Solution:
    def canWinNim(self,n:int)->bool:
        return bool(n % 4)  # 0,None,{},[],false的布尔值为false,其他为true 

Power button 852: Peak Mountain array index

We comply with the following attributes of an array Acalled mountain:

  • A.length >=3
  • There is 0 < i <A.length-1soA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

A given array is determined mountains, `return to meet any A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]of the ivalues.

Example 1:

输入:[0,1,0]
输出:1

Example 2:

输入:[0,2,1,0]
输出:1

Code:

class Solution:
    def peakIndexInMountainArray(self,A:List[int])->int:
        for i in range(1,len(A)-1):
            if A[i] > A[i-1] and A[I] > A[i+1]:
                return i

Outline of Solution: According to an example, it can be seen wherein the high mountains intermediate and low sides. At the same time do not take the first and last number. Mountains meet the conditions can be output i.

Stay button 1025: Game divisor

Alice and Bob play a game, they take turns. Alice upper hand start.

Initially, there is a number N on the board. In each player's turn, the player needs to do the following:

Is selected as an x, satisfying 0 <x <N, and N% x == 0.
Replacement digital x N on the board - with N.
If the player can not perform these operations, it will lose the game.

Only Alice returns True only when the victory in the game, otherwise false. Suppose that two players are in the best state to participate in the game.

Example 1:

输入:2
输出:true
解释:爱丽丝选择1,鲍勃无法进行操作。

Example 2:

输入:3
输出:false
解释:爱丽丝选择1,鲍勃也选择1,然后爱丽丝无法进行操作。
class Solution:
    def divisorGame(self,N:int)->bool:
        return N % 2 == 0

Analysis: When N is even, Alice victory.

Stay button: increase or decrease string matching

Containing only given "I"(increase) or "D"string (reduction) of the "D"string (decreased) S, so N=S.length.

Back [0,1,...,N]randomly arranged Asuch that for all i=0,...,N-1, have "

  • in caseS[i] == "I",那么A[i] < A[i+1]
  • If S[i] == "D", thenA[i] > A[i+1]

Example 1:

输出:"IDID"
输出:[0,4,1,3,2]

Example 2:

输出:"III"
输出:[0,1,2,3]
class Solution:
    def diStringMatch(self,S:str)->List[int]:
        left = 0
        right = len(S) # 长度
        A = []
        for i in S:
            if i =='I': # 'I'从小到大添加
                A.append(left)
                left += 1
            else:  # 'D'从大到小添加
                A.append(right)
                right -= 1
        A.append(right) # 不在S中的,从小到大添加
        return A

The number of bits: the force buckle 191

A write function, the input is an unsigned integer, which returns the number of digits in the binary expression '1' (also called Hamming weight).

Example 1:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'

Example 2:

输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串00000000000000000000000010000000 中,共有一位为'1'。

Solution one:

class Solution(object):
    def hammingWeight(self,n):
        return str(bin(n).count('1'))

Solution two:

Manually counting the number of cycles 1.

class Solution(object):
    def hammingWeight(self,n):
        n = bin(n)
        count = 0
        for c in n:
            if c == "1":
                count += 1
        return count        

Solution three:

Decimal binary transfer mode. Every time I take the judgment on whether the 2 1, then it iscount = count+1

class Solution:
    def hammingWeight(self,n):
        count = 0
        while n:
            res = n % 2
            if res == 1:
                count += 1
            n //= 2
        return count    

Solution four:

Bit algorithms.

And n 1 and the operation and the resulting nminimum number. Therefore, the minimum number of bits can be removed, and then nthe right one. Cycle this step until nzero.

class Solution(object):
    def hammingWeight(self,n):
        count = 0
        while n:
            count += n & 1
            n >>= 1
        return count    

Power button 784: capitalization full array

Given a string S, the string through Seach letter into the case, we can get a new string, the string returns a collection of all possible get.

示例:
输入:S = "a1b2"
输出:["a1b2","a1B2", "A1b2", "A1B2"]

输入:S = "3z4"
输出:["3z4","3Z4" ]

输入:S = "12345"
输出:["12345"]

note:

  • Length S no more than 12
  • S only by numbers and letters,
class Slution(object):
    def letterCasepermutation(self,S):
        res = [S]  # 无论大小写现将自身添加上去
        for i in range(len(S)):  # 循环 
            if S[i].isalpha():  # 
                for st in res[:]:
                    l = list(st)
                    if S[i].islower():
                        l[i] = S[i].upper()
                        res.append(''.join(l))
                    else:
                        l[i] = S[i].lower()
                        res.append(''.join(l))
        return res              

Guess you like

Origin www.cnblogs.com/zuihoudebieli/p/11161594.html