leetcode之算法

mac2022-06-30  70

一、两数之和#解法1class Solution(object):def twoSum(self, nums, target): lens = len(nums)for i in range(0,lens):for j in range(i+1,lens): num1 = nums[i] num2 = nums[j]if (num1 + num2 == target):# m = nums.index(num1) # n = nums.index(num2) lis = [i,j] return (lis) twoSum(0,[4,3,2], 5)#解法2class Solution(object):def twoSum(self, nums, target): j = -1 lens = len(nums)for i in range(1,lens): temp = nums[:i]if (target - nums[i]) in temp: j = temp.index(target - nums[i])break if j >= 0: lis = [j,i]return (lis) twoSum(0,[4,3,2], 5) 二、整数反转# -*- coding:utf-8 -*-class Solution:def reverse(self, x: int) -> int:#转为列表且反转 lst = list(str(x)) lst.reverse()#判断第一项是否为0 if lst[0] == 0: lst.popleft()#转为str,且取不到-1 ans = ''.join(lst[:-1])if lst[-1] == '-': ans = '-'+anselse: ans = ans + lst[-1] ans = int(ans)if -2**31 <= ans <=2**31-1:return anselse:return 0 reverse(0, 235)   三、回文数class Solution:def isPalindrome(self, x: int) -> bool:return str(x)[::-1] == str(x) isPalindrome(0,10)

转载于:https://www.cnblogs.com/xiaojingjingzhuanshu/p/11539879.html

相关资源:Leetcode面试算法题(Golang版)
最新回复(0)