【算法】最长连续序列、最小栈

79 阅读2分钟

128、 最长连续序列

0. 题面

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4

示例 2:

输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

提示:

1. 0 <= nums.length <= 10^5
2. -10^9 <= nums[i] <= 10^9

解法

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function (nums) {
  if (nums.length === 0) return 0;
  const arr = Array.from(new Set(nums)).sort((a, b) => a - b);
  console.log('arr:', arr);
  let count = 0;
  let temp = 1;
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] + 1 === arr[i + 1]) {
      temp++;
    } else {
      count = Math.max(count, temp);
      temp = 1;
    }
  }
  return Math.max(count, temp);
};

思路:

  • 先去重,再排序
  • 遍历数组,如果当前元素 + 1 等于下一个元素,则 temp++,否则,count = Math.max(count, temp),temp = 1
  • 时间复杂度 O(n),空间复杂度 O(n)
  • 也可以使用哈希表,存储每个元素是否存在,然后遍历数组,如果当前元素 - 1 不存在,则开始计算连续序列的长度

155、最小栈

0. 题面

设计一个支持 pushpoptop 操作,并能在常数时间内检索到最小元素的栈。

实现 MinStack 类:

  • MinStack() 初始化堆栈对象。
  • void push(int val) 将元素 val 推入堆栈。
  • void pop() 删除堆栈顶部的元素。
  • int top() 获取堆栈顶部的元素。
  • int getMin() 获取堆栈中的最小元素。

示例 1:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

提示:

1. `-2^31 <= val <= 2^31 - 1`
2. `pop``top``getMin` 操作总是在 非空栈 上调用
3. `push, `pop`, `top`, and `getMin`最多被调用 `3 * 10^4` 次

解法

var MinStack = function () {
  this.stack = [];
  this.minStack = [Infinity];
};

**
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {
  this.stack.push(val);
  this.minStack.push(Math.min(this.minStack[this.minStack.length - 1], val));
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  this.stack.pop();
  this.minStack.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.stack[this.stack.length - 1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
  return this.minStack[this.minStack.length - 1];
};

思路:

  • 使用两个栈,一个栈用来存储数据,另一个栈用来存储当前栈中的最小值。
  • 每次 push 时,将当前栈中的最小值和新值比较,将较小的值存入最小值栈中。
  • pop 时,两个栈同时弹出栈顶元素。
  • top 时,返回数据栈的栈顶元素。
  • getMin 时,返回最小值栈的栈顶元素。
  • 时间复杂度:O(1)
  • 空间复杂度:O(n)