• LeetCode算法题---第2天


    注:大佬解答来自LetCode官方题解

    80.删除有序数组的重复项Ⅱ

    1.题目

     

     2.个人解答

    1. var removeDuplicates = function (nums) {
    2. let res = [];
    3. for (let index = 0; index < nums.length; index++) {
    4. let num = 0;
    5. if (res.includes(nums[index])) {
    6. for (let i = 0; i < res.length; i++) {
    7. if (res[i] == nums[index]) {
    8. num++;
    9. }
    10. }
    11. if (num < 2) {
    12. res.push(nums[index]);
    13. }
    14. //得到num的次数
    15. if (num > 2) {
    16. return;
    17. }
    18. } else {
    19. res.push(nums[index]);
    20. }
    21. }
    22. nums.length=res.length
    23. for (let index = 0; index < res.length; index++) {
    24. nums[index]=res[index]
    25. }
    26. };

    3.大佬解答

    1. var removeDuplicates = function(nums) {
    2. const n = nums.length;
    3. if (n <= 2) {
    4. return n;
    5. }
    6. let slow = 2, fast = 2;
    7. while (fast < n) {
    8. if (nums[slow - 2] != nums[fast]) {
    9. nums[slow] = nums[fast];
    10. ++slow;
    11. }
    12. ++fast;
    13. }
    14. return slow;
    15. };

    169.多数元素

    1.题目

    2.个人解答

    1. var majorityElement = function (nums) {
    2. let result = 0;
    3. const res = Array.from(new Set([...nums]));
    4. res.forEach((item_nums) => {
    5. let n = nums.length / 2;
    6. nums.forEach((item_res) => {
    7. if (item_nums == item_res) {
    8. n = n - 1;
    9. }
    10. });
    11. if (n < 0) {
    12. result = item_nums;
    13. }
    14. });
    15. return result;
    16. };

    3.大佬解答

    没解答

    189.轮转数组

    1.题目

    2.个人解答

    1. var rotate = function (nums, k) {
    2. for (let index = 0; index < k; index++) {
    3. nums.unshift(nums[nums.length - 1]);
    4. nums.pop();
    5. }
    6. };

    3.大佬解答

    1. var rotate = function(nums, k) {
    2. const n = nums.length;
    3. const newArr = new Array(n);
    4. for (let i = 0; i < n; ++i) {
    5. newArr[(i + k) % n] = nums[i];
    6. }
    7. for (let i = 0; i < n; ++i) {
    8. nums[i] = newArr[i];
    9. }
    10. };

    1. const reverse = (nums, start, end) => {
    2. while (start < end) {
    3. const temp = nums[start];
    4. nums[start] = nums[end];
    5. nums[end] = temp;
    6. start += 1;
    7. end -= 1;
    8. }
    9. }
    10. var rotate = function(nums, k) {
    11. k %= nums.length;
    12. reverse(nums, 0, nums.length - 1);
    13. reverse(nums, 0, k - 1);
    14. reverse(nums, k, nums.length - 1);
    15. };

  • 相关阅读:
    Vertica 向 GBase8a 迁移指南之布尔数据类型(BOOLEAN)
    Bug分级处理指南:优先级与严重性的平衡
    java框架 Mybatis介绍与入门案例
    金仓数据库 KingbaseES 插件DBMS_OUTPUT
    浅析实施WMS仓储管理系统项目的几个要点
    stable diffusion , parameters in Outpainting
    Qt开发环境搭建
    【OpenCV 例程300篇】234. 特征提取之主成分分析(PCA)
    流程控制(下)
    牛客小白月赛52 E 分组求对数和(容斥定理+二分)
  • 原文地址:https://blog.csdn.net/m0_71469120/article/details/133363988