刷题42(力扣2道题)

75. 滑动窗口的最大值

题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof

题目描述
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。

示例:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:

滑动窗口的位置 最大值


[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

提示:

你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。

关键技术

  1. 提取k长度的数组,使用slice函数;
  2. 获取数组中最大的值:Math.max.apply(Math,arr))。
    题目分析
  3. 若是字符串长度为0,返回空数组;
  4. 若字符串长度不为空,以k为单位提取字符串;
  5. 比较提取后的字符串的和,取出最大值。
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function(nums, k) {
    if(!nums.length) return [];
    let sum = [];
    for(let i=0;i+k<=nums.length;i++){
      let arr = nums.slice(i, i+k);
      sum.push(Math.max.apply(Math,arr));   //获取数组最大的值
    }
    return sum;
};

76. 多数元素

题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

题目描述
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:
输入: [3,2,3]
输出: 3

示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2

关键技术
解法一:sort排序
解法二:投票法

题目分析
解法一:

  1. 写sort函数,把数组值按从小到大排序;
  2. 因为多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素,所以数组排序后多数元素肯定在数组长度1/2的位置;
  3. 输出排序后数组长度1/2位置的值。
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    nums.sort(function(a,b){
        return a-b;
    });
    let len = nums.length;
    let index = Math.ceil((len-1)/2);
    return nums[index];
};

解法二:

  1. 定义count:记录元素个数,定义res:存放数组的值;
  2. 遍历数组,若是count等于0,把当前数组中的元素赋值给res,并设置count = 1;
  3. 若是count不为0,比较当前元素与res是否相等,若相等,count加1,若不等,count减1;
  4. 返回res。
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    let count = 0;
    let res = nums[0];
    for(let i=0;i<nums.length;i++){
        if(count === 0){
            res = nums[i];
            count = 1;
        }else if(res === nums[i]){
            ++count;
        }else if(res !== nums[i]){
            --count;
        }
    }
    return res;
};

解法一耗时:112ms;

解法二耗时:72ms。
在这里插入图片描述

发布了75 篇原创文章 · 获赞 4 · 访问量 3106

猜你喜欢

转载自blog.csdn.net/weixin_41796393/article/details/104844405
今日推荐