zoukankan      html  css  js  c++  java
  • leetcode刷题18

    j今天刷的题是LeetCode26题,题目要求是给定一个排序数组,要求删除其中重复的元素

    并且不能申请额外的数组空间,必须原地操作,以及空间复杂度为01

    首先是来看我自己的代码,我是这样想的,当找到重复的元素的时候,就把数组后面整体的元素都往前移动,因此重点就成了如何找到重复元素的个数,也就是移动的间隔

    具体地代码如下:

    public static int solution1(int []nums){
            int length=nums.length;
            int count;
            int i=0;
            while (i<length-1){
                count=0;
                int j=i+1;
                while (j<length){
                    if (nums[j]==nums[i]){
                        count++;
                    }else {
                        break;
                    }
                    j++;
                }
                move(nums,i,count);
                length=length-count;
                i++;
            }
            return length;
        }
        public static void move(int [] nums,int start,int interval){
            while (start<nums.length-interval){
                nums[start]=nums[start+interval];
                start++;
            }
        }

    然后提交了之后,时间复杂度较高,116ms,因此去参考了LeetCode的官方解答思路。发现更为巧妙。

    同样地,需要查找相同元素的个数,我的方法是吧数组整体元素都搬迁移动,而LeetCode的思路是只移动不相等的那个元素,那么最后就是前n个元素就好了

    同样地,我也试了一把,代码如下:

    class Solution {
        public int removeDuplicates(int[] nums) {
            if (nums.length==0) {
                return 0;
            }else {
                int i=0;
                for (int j = 1; j <nums.length ; j++) {
                    if (nums[i]!=nums[j]){
                        i++;
                        nums[i]=nums[j];
                    }
                }
                return i+1;
            }
        }
    }

    时间一下子就缩短到2ms,提升可谓巨大

  • 相关阅读:
    学校的SQLServer的笔记
    Javaの集合学习
    XML的学习
    Java中学校没学过的东西
    MySQL的学习
    牛顿法及其收敛性
    c++编码规范
    C++标准库
    MATLAB编程技巧
    Matlab学习记录(函数)
  • 原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11425128.html
Copyright © 2011-2022 走看看