python + LeetCode思路代码

本文介绍了使用Python解决LeetCode上的一些经典问题,包括已排序数组的Two Sum、未排序数组的Two Sum、整数反转、Buddy Strings以及Reach a Number。通过双指针技术、字典存储、位运算等方法,详细阐述了解题思路和代码实现。
摘要由CSDN通过智能技术生成

目录

1.Two sum(sort)

2. two sum  

3.Reverse Integer

4.Buddy Strings


1.Two sum(sort)

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

思路:由于数组已经排序,因此可以使用双指针完成。

         定义i,j分别指向List的开头和结尾,定义tmp = nums[i] + nums[j]

         当tmp >  target,说明需要减少tmp值,则将j指针移动:j--

         当tmp < target,说明需要增加tmp值,则将i指针移动:i++

         当tmp =  target,找到答案。

代码:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i = 0
        j = len(numbers)-1
        res = []
        while(i<j):
            tmp = numbers[i]+numbers[j]
            if tmp > target:
                j -= 1
            elif tmp < target:
                i+=1
            else:
                res.append(i+1)
                res.append(j+1)
                i += 1
        return res

 

2. two sum  

https://leetcode.com/problems/two-sum/

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:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dis = {}
        for i in range(len(nums)):
            if target - nums[i] in dis:
                return [dis[target - nums[i]],i]
            else:
                dis[nums[i]] = i
        return []

 

3.Reverse Integer

https://leetcode.com/problems/reverse-integer/

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 store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路:这个就是将整数利用求余拆分位数,然后将其移动到对应位置。注意正负号以及是否溢出

代码:

class Solution:
    def reverse(self, x: int) -> int:
        res = 0
        flag = 0
        if x<0:
            flag =1
            x = -x
        while True:
            print(res)
            mod = x%10
            res = res*10+mod
            x =int(x/10)
            if x == 0:
                break
        if flag:
            if res > 2**31:return 0
            return -res
        else:
            if res > 2**31-1:return 0
            return res
        

 

4.Buddy Strings

https://leetcode.com/problems/buddy-strings/submissions/

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

 

Example 1:

Input: A = "ab", B = "ba"
Output: true

Example 2:

Input: A = "ab", B = "ab"
Output: false

Example 3:

Input: A = "aa", B = "aa"
Output: true

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false
Note:
  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A and B consist only of lowercase letters.

思路:因为只能调换一次,因此A和B之间要不全部相等,要不又两处地方不等。

所以有case1:A = B且A中至少有一个重复字母,如A= ‘ab’,B =‘ab’,这种情况调换后就不相等了。

case2:A[i] !=B[i],A[j] !=B[j], and A[i] ==B[j],A[j] ==B[i]。这种情况下,除了i,j其他字母A ,B要全相等才满足题目。

除了上述两种情况,其他情况都是不满足的。

代码:

class Solution:
    def buddyStrings(self, A: str, B: str) -> bool:
        if len(A) != len(B):return False
        if A==B and len(A) == len(set(A)): return False #排除case1
        dif = 0
        index = []
        for i in range(len(A)):
            if dif>2:return False
            if(A[i] != B[i]):
                dif+=1
                index.append(i)
        #判断case2
        if dif == 0:return True
        elif dif == 1:return False
        else:
            if A[index[0]] == B[index[1]] and B[index[0]] == A[index[1]]:
                return True
            else: return False
        
        

 

5. Reach a Number(754)

You are standing at position 0 on an infinite number line. There is a goal at position target.

On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.

Return the minimum number of steps required to reach the destination.

Example 1:

Input: target = 3
Output: 2
Explanation:
On the first move we step from 0 to 1.
On the second step we step from 1 to 3.

 

Example 2:

Input: target = 2
Output: 3
Explanation:
On the first move we step from 0 to 1.
On the second move we step  from 1 to -1.
On the third move we step from -1 to 2.

 

Note:

  • target will be a non-zero integer in the range [-10^9, 10^9].

解题思路:首先对于因为数字是关于0对称的,因此可以只考虑整数的情况。

步骤一:判断正负 target = math.fabs(target)

步骤二:假定sum = 1+2+3+....k 且 sum > target; diff = sum - target;

              case1: 若diff 为偶数的话,target = sum- diff; 而diff的值可以在集合{1,2,3,....k}里面找到第i个满足 1+2+....i = diff;

                          所以target = i+1+i+2 +....k - 1-2-....i;因此只需要移动k步。

              case2:diff = 0,移动k步。

              case3:diff 为奇数时,当k+1为奇数时,diff' =sum' -target= 1+2+3+....k+k-1-target为偶数,存在一个i属于子集满足                                   case1条件,所以移动步数为k+1;当k+1为偶数时,diff‘为奇数,存在一个i属于子集满足case1条件,所以要多                            移动一步即k+2才能满足上述case2,所以移动步数为k+2

代码如下:

def reachNumber(self, target: int) -> int:
        target = math.fabs(target)
        
        tmp = 0

        while(tmp <target):
            tmp +=i
            i+=1
        i=i-1
        if(tmp == target):
            return i
        diff = tmp - target
        if diff%2 == 0:
            return i
        else:
            if (i+1)%2 == 0:
                return i+2
            else:
                return i+1

#或者使用利用i*(i+1)/2 >= target直接求得i
def reachNumber(self, target: int) -> int:
        target = math.fabs(target)
        
        tmp = 0
        i = math.ceil(math.sqrt(2*target+0.25)-0.5)
        tmp = i*(i+1)/2
        if(tmp == target):
            return i
        diff = tmp - target
        if diff%2 == 0:
            return i
        else:
            if (i+1)%2 == 0:
                return i+2
            else:
                return i+1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值