2.2 Linked List & Array

5.1 Linked List

• Dummy Node

• High Frequency •

reverse linked list

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        # write your code here
        pre = None
        while head!= None:
            temp = head.next
            head.next = pre 
            pre = head 
            head = temp 
        return pre

Reverse Linked List II

中文English

Reverse a linked list from position m to n.

Reverse Nodes in k-Groups

模拟法

Dummy Node:

链表结构发生变化时,就需要 Dummy Node

Partition List

中文English

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

双指针方法,用两个指针将两个部分分别串起来。最后在将两个部分拼接起来。 left指针用来串起来所有小于x的结点, right指针用来串起来所有大于等于x的结点。 得到两个链表,一个是小于x的,一个是大于等于x的,做一个拼接即可。

Merge Two Sorted Lists

中文English

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Swap Two Nodes in Linked List

中文English

Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.

Example

Example 1:

Example 2:

Notice

You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.

找到权值为 v1v2 的节点之后, 分情况讨论:

  • 如果二者本身是相邻的, 则一共需要修改三条边(即三个next关系) {a node} -> {v = v1} -> {v = v2} -> {a node}

  • 如果二者是不相邻的, 则一共需要修改四条边 {a node} -> {v = v1} -> {some nodes} -> {v = v2} -> {a node} (假定v1在v2前)

Reorder List

Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

先找到中点,然后把后半段倒过来,然后前后交替合并。

Rotate List

中文English

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Example 1:

Example 2:

Copy List with Random Pointer

中文English

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

HashMap version

Challenge

Could you solve it with O(1) space?

141 Linked List Cycle

快慢指针的经典题。 快指针每次走两步,慢指针一次走一步。 在慢指针进入环之后,快慢指针之间的距离每次缩小1,所以最终能相遇。

142 Linked List Cycle II

Intersection of Two Linked Lists中文

Sort List

在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。

merge sort&& fast sort

快排 -- 先找Pivot ,再把链表一分为三,分别是由小于,等于,和大于Pivot节点构成。把大于和小于pivot节点构成的两个链表排好(递归)。 最后把三个链表按照从小到大串成一个链表。

解法2:归并 -- 把链表分成左右两半。 分别排好。最后吧两个排好的链表合并。 时间复杂度没什么好说,都是O(nlogn)-平均值。 快排最坏O(n2)。 空间复杂度 都是O(1) 的。 由于链表的归并排序不用创建一个长度为N的list。

Convert Sorted List to Binary Search Tree

Dfs: 高度平衡,所以将链表从中间分开,左边是左子树,右边是右子树。

Delete Node in a Linked List

237

5.2 Array

• Subarray • Sorted Array

Merge Sorted Array:

88. Merge Sorted Array

  • 双指针

  • 倒序合并

Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. 分析:涉及两个有序数组合并,设置i和j双指针,分别从两个数组的尾部想头部移动,并判断Aiarrow-up-right和Bjarrow-up-right的大小关系,从而保证最终数组有序,同时每次index从尾部向头部移动。

  • 时间复杂度:

    O(n+m)

    ,n,m分别为A,B数组的元素个数

    • 利用双指针各自遍历一遍对应的数组;

  • 空间复杂度:

    O(1)

    • 只需要新建pointApointA,pointBpointB和indexindex三个整型变量;

349. Intersection of Two Arrays

350 Intersection of Two Arrays II

4. Median of Two Sorted Arrays

5.3 Subarray(prefix sum)

Maximum Subarray

T1: prefix sum:

令 PrefixSum[i] = A[0] + A[1] + ... A[i - 1], PrefixSum[0] = 0

易知构造 PrefixSum 耗费 O(n) 时间和 O(n) 空间

如需计算子数组从下标i到下标j之间的所有数之和 则有

Sum(i~j) = PrefixSum[j + 1] - PrefixSum[i]

Minimum Subarray: 乘-1变max

Subarray Sum

某一段l, rarrow-up-right的和为0, 则其对应presuml-1arrow-up-right = presumrarrow-up-right. presum 为数组前缀和。只要保存每个前缀和,找是否有相同的前缀和即可。

复杂度分析

  • 时间复杂度:O(n),n为整数数组的长度

  • 空间复杂度:O(n),n为整数数组的长度

  • 需使用hash表保存前缀和;

follow up:

Subarray Sum Closest

Time:O(nlogn)

Space:O(n)

\1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

\915. Partition Array into Disjoint Intervals

5.4 More

26 Remove Duplicates from Sorted Array

27. Remove Element

follow up: infinite array just calculate with live points

Last updated