前面的题目以后在慢慢补,我自己先从23题开始写起,刷leetcode对我的编码能力提高有很大的帮助
23.Merge K sorted lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
作为一个写python的,第一想法是直接用list把所有的结点的value全部记录,然后用sort排序,
所以我的第一写法是这样的
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
tmp = []
for item in lists:
while item:
tmp.append(item.val)
item = item.next
result = sorted(tmp)
return result
直接跑,居然成功了,我最后的输出都不是链表啊,只是一个列表
这是leetcode的bug么,
是否因为list也是一个有序数据组,然后最后判断的时候是一个数据一个数据来的,所以没有影响
但是根据题意,我们还是输出一个链表吧
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
tmp = []
for item in lists:
while item:
tmp.append(item)
item = item.next
tmp = sorted(tmp,key=lambda item : item.val)
result = ListNode(0)
result_tmp = result
for i in tmp:
result_tmp.next = i
result_tmp = result_tmp.next
result_tmp.next = None
return result.next
后面的就是将列表重新转换成链表了
肯定有一些想法是排序和链表生成一步完成的,那样的效果肯定好,但是leetcode上面使用Python3写的几乎都是这种思路,
即使速度最快的也是,
24 swap nodes in pairs
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed
题目写了控制空间,有个简单的写法,就是和上一题一样先转换list,在转回来
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
tmp = []
while head:
tmp.append(head.val)
head = head.next
i = 0
while i+1<len(tmp):
tmp[i+1],tmp[i] = tmp[i],tmp[i+1]
i +=2
return tmp
我这边一样缺少了一个将list转换为链表的步骤,这边就不写了,因为速度肯定慢,写了没意义
下面这个是一个非常好的解答,1.省内存,2.速度快,
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
p = dummy
dummy.next = head
while (p.next != None and p.next.next != None):
tmp = p.next.next
p.next.next = tmp.next
tmp.next = p.next
p.next = tmp
p = tmp.next
return dummy.next
25.Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
这题是上一题的升级版,还是可以用列表解决,Python中的list有点BUG
一样可以解决
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tmp = []
while head:
i = 0
tmp_1 = []
while i < k and head:
tmp_1.append(head.val)
head = head.next
i += 1
if i==k:
tmp_1 = list(reversed(tmp_1))
tmp.extend(tmp_1)
return tmp
Runtime: 68 ms, faster than 43.59% of Python3 online submissions for Reverse Nodes in k-Group.
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None or k<2:
return head
ret = head
for i in range(k-1):
ret = ret.next
if ret is None:
return head
prev, current = None, head
for i in range(k):
_next = current.next
current.next = prev
prev = current
current = _next
head.next = self.reverseKGroup(current, k)
return ret
上面的思路不是我写的,是一位大牛,用迭代的思想写,速度是真的快
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 ofnums
being1
and2
respectively.It doesn't matter what you leave beyond the returned length. Example 2: Given ums [0,0,1,1,1,2,2,3,3,4],Your function should return length =5
, with the first five elements fnums
being modified to0
,1
,2
,3
, and4
respectively.It doesn't matter what values are set beyond the returned length. Clarification:Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
给定的列表是有序的,那么我们只需要返回列表中不重复的值的有序排列和它们的数量
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 1
for i in range(1,len(nums)):
if nums[i] != nums[i-1]:
nums[k] = nums[i]
k += 1
return k if len(nums)>0 else 0
代码思路,由于是有序的,每当前后不相同的时候就说明遇到了一个新的值,那么就将这个值与前面的值调换,并且k+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 ofnums
containing0
,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. Clarification:Confused why the returned value is an integer but your answer is an array?Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while val in nums:
nums.remove(val)
return len(nums)
28 impleament strStr()
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
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle!="":
if needle in haystack:
return haystack.index(needle)
elif needle not in haystack:
return -1
else:
return 0
28. Implement strStr()
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
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle!="":
if needle in haystack:
return haystack.index(needle)
elif needle not in haystack:
return -1
else:
return 0
特简单,不详解了,大家应该看得懂
29. Divide Two Integers
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- 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 231 − 1 when the division result overflows.
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
def helper(u,d):
if u<d:
return 0
num=1
temp = d
while (temp+temp)<=u:
num=num+num
temp = temp+temp
return num+helper(u-temp,d)
flag = 1
if dividend>0 and divisor<0:
flag=-1
if dividend<0 and divisor>0:
flag=-1
up = abs(dividend)
down = abs(divisor)
res = helper(up,down)
if res*flag>2**31-1:
return 2**31-1
if res*flag<-2**31:
return -2**31
return res*flag
利用迭代是很明显的,
重要是确定正负号 和 数字的阈值,只要把这个做好一切就ok了
30. Substring with Concatenation of All Words
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []