Leetcode刷题笔记(持续更新...)
1.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].
暴力算法时间复杂度为O(n^2),不可取
方法一:
时间复杂度O(n)算法:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
temp = 0
for i,j in enumerate(nums): #i存储nums的索引
temp = target - j
if j in dic:
return [dic[j],i]
dic[temp] = i #dic的值存储nums的索引,键存储该索引对应的nums值与target的差
7.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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = int(str(abs(x))[::-1])
return s * ((x > 0) - (x < 0)) * (s <= 2 ** 31 - 1)
9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
要求不将×××转化为字符串处理
return str(x)==str(x)[::-1] #虽然简单,但不符此题要求
解:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
range = 1
while x // range >= 10:
range *= 10
while x:
left = x // range #取最高位
right = x % 10 #取个位
if left != right:
return False
x = (x % range) // 10 #掐头去尾
range = range // 100 #x每次减少两位
return True
13. Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
摘自*:
罗马数字共有7个,即Ⅰ(1)、Ⅴ(5)、Ⅹ(10)、Ⅼ(50)、Ⅽ(100)、Ⅾ(500)和Ⅿ(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有“0”,与进位制无关。一般认为罗马数字只用来记数,而不作演算。重复数次:一个罗马数字重复几次,就表示这个数的几倍。
右加左减:
在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
但是,左减时不可跨越一个位值。比如,99不可以用IC(100-1)表示,而是用XCIX( [100-10]+[10-1])表示。(等同于阿拉伯数字每位数字分别表示。)
左减数字必须为一位,比如8写成VIII,而非IIX。
右加数字不可连续超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)加线乘千:
在罗马数字的上方加上一条横线或者加上下标的Ⅿ,表示将这个数乘以1000,即是原数的1000倍。
同理,如果上方有两条横线,即是原数的1000000(1000^2)倍。数码限制:
同一数码最多只能连续出现三次,如40不可表示为XXXX,而要表示为XL。
例外:由于IV是古罗马神话主神朱庇特(即IVPITER,古罗马字母里没有J和U)的首字,因此有时用IIII代替IV。
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = {'I':1, 'X':10, 'C':100, 'M':1000, 'V':5, 'L':50, 'D':500}
prev = 0
sum = 0
for i in s[::-1]:
curr = dic[i]
if prev > curr:
sum -= curr
else:
sum += curr
prev = curr
return sum
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
取最长前缀
方法一:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
length=0
for i in zip(*strs):
if len(set(i)) > 1:
break
else:
length+=1
return strs[0][:length]
20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dic = {')':'(', ']':'[', '}':'{'}
temp = []
for i in s:
if i in dic.values():
temp.append(i)
elif i in dic.keys():
if temp == [] or dic[i] != temp.pop():
return False
return temp == []
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
26. Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
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.
It doesn't matter what you leave beyond the returned length.
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.
It doesn't matter what values are set beyond the returned length.
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return
cnt = 0
for i in range(1,len(nums)):
if nums[i] != nums[cnt]:
cnt += 1
nums[cnt] = nums[i]
return cnt + 1
27. Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
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.
It doesn't matter what you leave beyond the returned length.
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.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
start, end = 0, len(nums) - 1
while start <= end:
if nums[start] == val:
nums[start], nums[end] ,end = nums[end], nums[start], end - 1
else:
start += 1
return start
28. Implement strStr()
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
length = len(needle)
for i in range(len(haystack) - length + 1):
if haystack[i : i + length] == needle:
return i
return - 1
35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
result = nums.index(target)
except ValueError:
if target < nums[0]:
return 0
if target > nums[-1]:
return len(nums)
for i in range(len(nums)):
if nums[i] <= target <= nums[i + 1]:
return i + 1
return result
社区答案
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return len([x for x in nums if x<target])
class Solution:
def searchInsert(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return low
转载于:https://blog.51cto.com/11281400/2103588
上一篇: 数据结构和算法:递归
推荐阅读
-
【leetcode刷题】九月leetcode打卡每日记录(持续更新)
-
【LeetCode刷题日记】持续更新中...
-
Leetcode刷题笔记(持续更新...)
-
leetcode刷题笔记(1-10)持续更新中
-
Leetcode刷题——持续更新
-
LeetCode刷题总结(持续更新中。。。)
-
LeetCode刷题:233. Number of Digit One
-
LeetCode刷题:260. Single Number III
-
LeetCode刷题:20. Valid Parentheses
-
LeetCode刷题:349. Intersection of Two Arrays&350. Intersection of Two Arrays II