C/C++教程

【手把手带你刷Leetcode力扣】1.算法 - 双指针

本文主要是介绍【手把手带你刷Leetcode力扣】1.算法 - 双指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  • 普通双指针:两个指针往同一个方向移动
  • 对撞双指针:两个指针面对面移动(有序数列)
  • 快慢双指针:慢指针+快指针(环形链表)

141.环形链表

class Solution:
	# Time Complexity: O(N)
	# Space Complexity: O(1)
	def hasCycle(self, head: ListNode) -> bool:
		if head is None:
			return False
		slow = head
		fast = head
		while fast is not None and fast.next is not None:
			fast = fast.next.next
			slow = slow.next
			if slow == fast:
				return True
		
		retrun False

881.救生艇

class Solution:
	# Time Complexity: O(NlogN)
	# Space Complexity: O(1)
	def numRescueBoats(self, people: List[int], limit: int) -> int:
		if people is None or len(people) == 0:
			retrun 0
		people.sort()
		i = 0
		j = len(people) - 1
		res = 0
		while (i <= j):
			if people[i]+people[j] <= limit:
				i = i + 1
			j = j - 1
			res = res + 1
		return res

学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣

这篇关于【手把手带你刷Leetcode力扣】1.算法 - 双指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!