一个小小白。。开始leetcode刷题。
是跟着这个视频学的。https://space.bilibili.com/405863549/video
小姐姐讲的很好。易懂。然后我跟着敲了一遍代码。记录下来。
class Solution: def twoSum1(self, nums, target): for i in nums: j = target - i start_index = nums.index(i) next_index = start_index + 1 temp_index = nums[next_index:] if j in temp_index: return [nums.index(i),next_index+temp_index.index(j)]
(2) 第二种解法。方便。
class Solution: def twoSum(self, nums, target) : dict ={} for i in range(len(nums)): if target - nums[i] not in dict: dict[nums[i]] = i else: return [dict[target-nums[i]],i]
2.第七题:(简单):Reverse Integer 转置整数
Given a 32-bit signed integer, reverse digits of an integer.
(1)Example 1:
Input: 123
Output: 321
(2)Example 2:
Input: -123
Output: -321
需要注意的是,转置后的数不能溢出32位整数范围:[−2^31, 2^31 − 1];也就是[-2147483648,2147483647]
代码:
(1) 不推荐
class Solution:
def reverse(self, x):
num = 0 #将输出的数设为0
a = abs(x)
while(a != 0):
temp = a % 10 #取出个位数
num = num*10 + temp
a = int(a/10)
if x > 0 and num < 2147483647:
return num
elif x < 0 and num < 2147483648:
return -num
else:
return 0
(2)采用字符串的方法转置,简单。推荐
class Solution:
def reverse(self, x):
s = str(x)[::-1].rstrip("-")
if int(s) < 2**31:
if x > 0:
return int(s)
else:
return 0 - int(s)
return 0
代码:
(1) 复杂,不推荐
class Solution:
def isPalindrome(self, x):
num = 0
a = abs(x)
while(a!=0):
temp = a % 10
num = num *10 + temp
a = a // 10
if x >= 0 and x == num:
return True
else:
return False
(2)采用字符串方法。简单
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
s = str(x)[::-1]
if int(s) == x:
return True
else:
return False
4.第13个题(简单):
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
一般罗马数字都是按照,从左到右,从大到小排列的。但也有比如,后面一位代表的数,比前面一位大的时候,就用后面一位减去前面一位。
比如:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
例子:
(1)Example 1:
Input: “III”
Output: 3
(2)Example 2:
Input: “IV”
Output: 4
(3)Example 3:
Input: “IX”
Output: 9
(4)Example 4:
Input: “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.
(5)Example 5:
Input: “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
代码:
class Solution:
def romanToInt(self, s):
result = 0
numeral_map = {"I" : 1, "V": 5, "X": 10, "L": 50, 'C': 100,\
"D": 500, "M" :1000}
for i in range(len(s)):
if i >0 and numeral_map[s[i]] > numeral_map[s[i-1]]:
result += numeral_map[s[i]] - 2 * numeral_map[s[i-1]]
else:
result += numeral_map[s[i]]
return result
以例5为例,因为后面一位减去前面一位的时候(M-C),前面一位已经加过了(变成:M+C+M-C),但我们想要得到的结果是M+(M-C),所以要再减去1次C,就是前面的数。所以代码中要×2
5 .第14题(简单):Longest Common Prefix 最大的相同前缀
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
(1)Example 1:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
(2)Example 2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
代码:
有两种解法:
① 第一种解法:就是用第一个数作为参考,后面的数不断和第一个数比较。
class Solution:
def longestCommonPrefix(self, strs):
if not strs: # 如果没有strs
return ""
for i in range(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or strs[0][i] != string[i]:
return strs[0][:i]
return strs[0] #有strs,但里面的符号是空
② 第二种解法:用到 zip 和 set
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = ""
zzip = zip(*strs)
# 解压,返回一个由各个元祖组成的数组。长度为strs中最小序列的长度
for temp in zzip:
temp_set = set(temp)
if len(temp_set) == 1:
result += temp[0]
else:
break
return result
(1)Example 1:
Input: “()”
Output: true
(2)Example 2:
Input: “()[]{}”
Output: true
(3)Example 3:
Input: “(]”
Output: false
(4)Example 4:
Input: “([)]”
Output: false
(5)Example 5:
Input: “{[]}”
Output: true
“”"
代码:
class Solution:
def isValid(self, s) :
stack = []
lookup = {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0
注意要考虑特殊情况:(1)“]” 就是只有一个右边的括号,是错的。此时第八行的len(stack)== 0 (2)“[” 只有一个左边的括号也是错的,放在最后来判断。就是 return len(stack) == 0时候返回false
7.第21题(简单) Merge Two Sorted Lists 合并两个已经排好序的列表
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
主要思想:
新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,
由于两个输入链表的长度可能不同(但都是排好序的),
所以最终会有一个链表先完成插入所有元素,则直接另一个未完成的链表直接链入新链表的末尾。
代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur = dummy = ListNode(0) #创建一个头节点
# dummy:虚拟的node,一直指向原点。为了最后返回结果
while l1 and l2: # 遍历l1和l2
if l1.val < l2.val:
cur.next = l1
cur = cur.next
l1 = l1.next
else:
cur.next = l2
cur = cur.next
l2 = l2.next
cur.next = l1 or l2
return dummy.next
(1)Example 1:
Given nums = [1,1,2],
Your function should return length = 2,
with the first two elements of nums being 1 and 2 respectively.
(2)Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5,
with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
该题的主要思想是,是要设立一个游标指向原点,然后循环,遇到相同的数时游标就不动,不同的数时游标就前进一位,并赋予当前这个不同的数。
代码:
class Solution:
def removeDuplicates(self, nums) :
if not nums:
return 0
cur = 0 # 设置一个游标指向原点,但遇到不同的数时,才移动
for i in range(len(nums)):
if nums[cur] != nums[i]:
cur += 1
nums[cur] = nums[i]
return cur + 1
9.第27题 (简单) Remove Element 移动元素
Given an array nums and a value val,
remove all instances of that value in-place and return the new length.
(1)Example 1:
Given nums = [3,2,2,3], val = 3,
your function should return length = 2, with the first two elements of nums being 2.
(2)Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
思想:运用栈的思想,将数组看成一个栈,依次从后往前比较,若发现目标值将该元素出栈即可。
代码:
class Solution:
def removeElement(self, nums, val)
n = len(nums)
for i in range(n-1,-1,-1): # 逆序遍历(出栈是最后一个元素先出)
if nums[i] == val: # 与目标值相等
nums.pop(i) # 将该元素出栈
return len(nums) # 返回更新后数组的长度
10.第28题 Implement strStr() 简单题
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
(1)Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
(2)Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
代码:
(1)
class Solution:
def strStr(self, haystack, needle):
for i in range(len(haystack) - len(needle)+1): # 并不是遍历全部
if haystack[i:i+len(needle)] == needle:
return i
return -1
(2) 用到自带函数,index… 不过也要掌握上面方法
class Solution(object):
def strStr(self, haystack, needle):
if needle in haystack:
return haystack.index(needle)
else:
return -1