【leetcode】sort list(python)

链表的归并排序

超时的代码

class Solution:
	def merge(self, head1, head2):
		if head1 == None:
			return head2
		if head2 == None:
			return head1
		# head1 and head2 point to the same link list
		if head1 == head2:
			return head1

		head = None
		tail = None
		# the small pointer point to smaller of two.
		while head1 and head2:
			if head1.val <= head2.val:
				small = head1
				head1 = head1.next
			else:
				small = head2
				head2 = head2.next
			# the first node
			if tail == None:
				tail = small
				head = small
			else:
				tail.next = small
				tail = small
		# link the remaind nodes
		if head1 == None:
			head1 = head2

		tail.next = head1
		return head

	def sortList(self, head):
		if head == None or head.next == None:
			return head
		# we use a fast pointer which go two steps each time and
		# a slow pointer which go one step each time to get the
		# middle of the link list
		slow = head
		fast = head
		while fast.next and fast.next.next:
			fast = fast.next.next
			slow = slow.next
		# slow point to the middle now
		head2 = slow.next
		# we cut of the linked list at middle
		slow.next = None

		left = self.sortList(head)
		right = self.sortList(head2)
		return self.merge(left, right)

主要是在merge的时候。要推断第一个结点

AC代码

class Solution:
	def merge(self, head1, head2):
		if head1 == None:
			return head2
		if head2 == None:
			return head1
		# head1 and head2 point to the same link list
		if head1 == head2:
			return head1

		head = ListNode(-1)
		tail = head
		# the small pointer point to smaller of two.
		while head1 and head2:
			if head1.val <= head2.val:
				small = head1
				head1 = head1.next
			else:
				small = head2
				head2 = head2.next

			tail.next = small
			tail = small
		# link the remaind nodes
		if head1 == None:
			head1 = head2

		tail.next = head1
		return head.next

	def sortList(self, head):
		if head == None or head.next == None:
			return head
		# we use a fast pointer which go two steps each time and
		# a slow pointer which go one step each time to get the
		# middle of the link list
		slow = head
		fast = head
		while fast.next and fast.next.next:
			fast = fast.next.next
			slow = slow.next
		# slow point to the middle now
		head2 = slow.next
		# we cut of the linked list at middle
		slow.next = None

		left = self.sortList(head)
		right = self.sortList(head2)
		return self.merge(left, right)

这里merge的时候建立了一个伪头结点,处理的时候就不用推断是否为第一个结点,尽管AC,但时间5500ms以上。而c++代码仅仅须要200多ms,差距还是比較大的

时间: 2024-10-10 18:12:28

【leetcode】sort list(python)的相关文章

【leetcode】Word Break(python)

思路是这种.我们从第一个字符開始向后依次找,直到找到一个断句的地方,使得当前获得的子串在dict中,若找到最后都没找到.那么就是False了. 在找到第一个后,接下来找下一个断句处,当然是从第一个断句处的下一个字符開始找连续的子串,可是这时与第一个就稍有不同.比方说word='ab', dict={ 'a', ab', ...},在找到a后,接下来处理的是b.我们发现b不在dict中,可是我们发现b能够和a结合,形成ab,而ab在dict中.所以这里的每一个子串就能够有三种选择.要么自己单独作为

【leetcode】Clone Graph(python)

类似于二叉树的三种遍历,我们可以基于遍历的模板做很多额外的事情,图的两种遍历,深度和广度模板同样也可以做很多额外的事情,这里举例利用深度优先遍历的模板来进行复制,深度优先中,我们先访问第一个结点,接着访问第一个邻接点,再访问邻节点的邻节点.... class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if None =

【leetcode】Reverse Integer(middle)☆

Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 总结:处理整数溢出的方法 ①用数据类型转换long  或 long long ②在每次循环时先保存下数字变化之前的值,处理后单步恢复看是否相等 (比③好) ③整体恢复,看数字是否相等. 思路:注意30000这样以0结尾的数字,注意越界时返回0. 我检查越界是通过把翻转的数字再翻转回去,看是否相等. int rever

【leetcode】Happy Number(easy)

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the

【leetcode】3Sum Closest(middle)

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

【链表】Sort List(归并排序)

题目: Sort a linked list in O(n log n) time using constant space complexity. 思路: nlogn的排序有快速排序.归并排序.堆排序.双向链表用快排比较适合,堆排序也可以用于链表,单向链表适合用归并排序. /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */

【LeetCode】Reconstruct Itinerary(332)

1. Description Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. No

【leetcode】Word Break (middle)

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

【leetcode】Merge Intervals(hard)

Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]. 思路:开始想用线段树,后来想想这个不是动态变化的没必要. 按区间的第一个值从小到大排序,然后跳过后面被覆盖的区间来找. sort折腾了好久,开始搞不定只好自己写了一个归并排序.现在代码里的sort是可用的. class