给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
对于这道题,可以把所有小于x的节点都给取出来放在一个新的链表,再将所有大于等于x的节点取出来放在另一个新的链表,最后再进行链表的拼接即可
class Solution:
def partition(self, head, x):
low_head = ListNode('low_head')
#定义小弟(low_poiny)帮大哥(low_head )干活,
low_point = low_head
high_head = ListNode('high_head')
high_point = high_head
point = head
while point != None:
#对大于等于x的和小于x的进行分类分配到新链表
if point.val < x:
low_point.next = point
low_point = low_point.next
elif point.val >= x:
high_point.next = point
high_point = high_point.next
point = point.next
#连接链表【第一个链表尾节点+第二个链表头节点】
low_point.next = high_head.next
high_point.next = None
return low_head.next
三数之和:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
对于这道题:我想到的是冒泡的思路,但是时间复杂度是O(n^3),代码如下:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
first_loop = len(nums) - 2
second_loop = len(nums) - 1
last_loop = len(nums)
son_list = []
nums.sort()
for i in range(first_loop):
j = i + 1
for j in range(j,second_loop):
k = j + 1
for k in range(k, last_loop):
if nums[i] + nums[j] + nums[k] == 0:
tempList = [nums[i],nums[j],nums[k]]
if tempList not in son_list:
son_list.append(tempList)
tempList = []
return son_list
运行结果没错的,但是当给定的数组很大时,这个运行时间就很大了,从而导致了运行时间过长,查看了一下大神的代码,发现可以将第二三层循环给弄成一个循环的,将时间复杂度调至O(n^2),这样就不会导致上面时间运行过长的结果了,采用的是双指针的方式。代码见下:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res =[]
i = 0
for i in range(len(nums)-2):
if i == 0 or nums[i]>nums[i-1]:
l = i+1
r = len(nums)-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s == 0:
res.append([nums[i],nums[l],nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l-1]:
l += 1
while r > l and nums[r] == nums[r+1]:
r -= 1
elif s > 0:
r -= 1
else :
l += 1
return res