1. 兩數之和
題目:給定一個整數數組 nums
和一個目標值 target
,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。
思路:建立字典,遍歷差值是否在字典中。時間複雜度o(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i,key in enumerate(nums):
tmp = target-key
if tmp in dic:
return [dic[tmp],i]
dic[key] =i
return None
2. 兩數相加
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
思路:當前節點不爲兩個None時,將None變爲0值節點,記得進位。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res = []
jump = 0
node = ListNode(0)
while l1 or l2:
tmp = l1.val+l2.val+jump
res.append(tmp%10)
jump = 0
if tmp>=10:
jump = 1
l1 = l1.next
l2 = l2.next
if not l1 and l2:
l1 = node
if not l2 and l1:
l2 = node
if jump:
res.append(jump)
return res
3. 無重複字符的最長子串
給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。
思路:滑動窗口、當出現重複字母,beg變爲原字母索引+1(原beg小於新值)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
res = 0
beg = 0
for i in range(len(s)):
if s[i] not in dic:
dic[s[i]] = i
else:
if dic[s[i]]+1>beg:
beg = dic[s[i]]+1
dic[s[i]] = i
if (i-beg+1)>res:
res = i-beg+1
return res
7. 整數反轉
題目:給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
思路:過
class Solution:
def reverse(self, x: int) -> int:
y=x if x>0 else -x
z = 0
while y:
z = z*10+y%10
y //= 10
z=z if x>0 else -z
if z>=2**31 or z<-2**31:
return 0
else:
return z
題目:判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。
思路: 首先得到給出的x是一個幾位數,然後每次判斷當前x的第一位和最後一位是否相同,最後去掉x的前後兩位,繼續判斷。
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
n = 1
while x//n>=10:
n *=10
while x:
left = x//n
right = x%10
if left != right:
return False
x = x%n//10
n/=100
return True
題目:給定一個羅馬數字,將其轉換成整數。輸入確保在 1 到 3999 的範圍內。
思路:用字典轉換羅馬數,用大數左邊的數只有一個來判斷+還是-。
class Solution:
def romanToInt(self, s):
map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
num, pre = 0, 1000
for i in [map[j] for j in s]:
num, pre = num + i - 2 * pre if i > pre else num + i, i
return num
題目:編寫一個函數來查找字符串數組中的最長公共前綴。如果不存在公共前綴,返回空字符串 ""
。
思路:先找最短的字符串(肯定大於等於最長公共),再遍歷比較後面的字符。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
minlen = min([len(x) for x in strs])
end = 0
while end < minlen:
for i in range(1,len(strs)):
if strs[i][end]!= strs[i-1][end]:
return strs[0][:end]
end += 1
return strs[0][:end]
題目:給定一個只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判斷字符串是否有效。
有效字符串需滿足:
- 左括號必須用相同類型的右括號閉合。
- 左括號必須以正確的順序閉合。
class Solution:
def isValid(self, s: str) -> bool:
a = ['[]','{}','()']
ls = []
for i in s:
ls.append(i)
if len(ls)>=2 and (ls[-2]+ls[-1]) in a:
ls = ls[:-2]
return len(ls) == 0
題目:將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
node = ListNode(2009)
beg = node
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
if l1:
node.next = l1
else:
node.next = l2
return beg.next
題目:給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
a = nums[0]
i = 1
while i <len(nums):
if a != nums[i]:
a = nums[i]
i +=1
else:
nums.pop(i)
return len(nums)
給定一個數組 nums 和一個值 val,你需要原地移除所有數值等於 val 的元素,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
元素的順序可以改變。你不需要考慮數組中超出新長度後面的元素。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
while i <len(nums):
if nums[i] == val:
nums.pop(i)
else:
i+=1
return len(nums)
給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == '':
return 0
if needle not in haystack:
return -1
l = len(needle)
i = 0
while i < len(haystack):
if haystack[i:i+l] == needle:
return i
i+=1
return -1