一天一道算法题(持续更新)

day1 

Two Sum: https://leetcode.com/problems/two-sum/description/

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):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)-1):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j] == target:
                    return [i,j]

day2

Rotate String: https://leetcode.com/problems/rotate-string/description/

We are given two strings, A and B.

shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.

Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true

Example 2:
Input: A = 'abcde', B = 'abced'
Output: false

Note:

  • A and B will have length at most 100.

翻译:给定两个字符串A和B,将字符串A的字符依次从最头移到最尾,若A终能和B相等则返回True,否则返回False。

代码:

class Solution:
    def rotateString(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        if A == B:
            return True
        for i in range(len(A)):
            if A[i:]+A[:i]==B:
                return True
        return False

day3

Reverse Integer: https://leetcode.com/problems/reverse-integer/description/

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

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻译:给定一个整数,将其数字反转。当数字溢出时,返回0。

代码:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            y = -int(str(-x)[::-1])
        else:
            y = int(str(x)[::-1])
        if y < -2147483648 or y > 2147483648:
            return 0
        return y

  • day4

最近遇到瓶颈了,python都没研究明白的人,学dl真的好多坑啊。。。

你可能感兴趣的:(一天一道算法题(持续更新))