[56] Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
时间复杂度:
排序时间($O(NlogN)$) + 遍历数组($O(N)$)
空间复杂度: 直接借用js数组特性splice对原数组进行修改, 没有使用额外的空间. 因此为$O(1)$.
数组的sort方法:
当数组长度<=10的时候,采用插入排序($O(N^2)$),>10的时候,采用快排($O(NlogN)$)。
对于长度>1000的数组,采用的是快排与插入排序混合的方式进行排序.
1 | // 合并有交集的若干个区间 |
[57] Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
时间复杂度:
遍历了一遍数组, 后面的判断部分时间是常数级, 因此 $O(N)$.
不得不说, 思路很好耶, 很巧妙利用了题目所给的条件. 比如有序, 比如区间合并, 这里的区间合并显得尤其简单.
1 | // intervals 本身是已经排好序的 |
[169] Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than
⌊ n/2 ⌋times.You may assume that the array is non-empty and the majority element always exist in the array.
1 | // solution 1 |
[54] Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
时间复杂度:
遍历矩阵 $O(M*N)$.
空间复杂度:
除了返回的结果数组, 使用的额外空间为常数级, $O(1)$.
1 | // 旋转矩阵 |
[59] Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
借鉴上一题的思路.
时间复杂度: O(N*N), 遍历了整个二维数组.
空间复杂度: O(1), 除了返回的二维结果数组, 其余为常量级.
1 | var generateMatrix = function (n) { |
[48] Rotate Image
You are given an n x n 2D
matrixrepresenting an image, rotate the image by 90 degrees (clockwise).You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
时间复杂度:
双重循环 $O(N)$.
空间复杂度:
O(1). 原地修改数组内容.
1 | // 思路就是: 旋转完外圈, 再旋转内圈 |