• 删除排序数组中的重复数字 II · Remove Duplicates from Sorted Array II


    重复一次

    [抄题]:

    给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。

    不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。

    [思维问题]:

    [一句话思路]:

     不重复时,size扩大

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构,为什么不用别的数据结构]:

    [其他解法]:

    [Follow Up]:

    [题目变变变]:

     链表

    public class Solution {
        /*
         * @param nums: An ineger array
         * @return: An integer
         */
        public int removeDuplicates(int[] nums) {
            if (nums.length == 0 || nums == null) {
                return 0;
            }
            int size = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] != nums[size]) {
                    nums[++size] = nums[i];
                }
            }
            return size + 1;
        }
    }
    View Code

    重复多个

    [抄题]:

    What if duplicates are allowed at most twice?

    For example,
    Given sorted array nums = [1,1,1,2,2,3],

    Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

    [思维问题]:

    不知道怎么改变数组中元素的个数:其实只要调整角标 加减就行了

    [一句话思路]:

    用count < 2控制,不同元素时,size只加一次

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    count控制了所有元素的重复情况,没有重复时,恢复count = 1

    [总结]:

    注意恢复count = 1

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构,为什么不用别的数据结构]:

    [其他解法]:

    [Follow Up]:

    [题目变变变]:

     链表

    public class Solution {
        /**
         * @param A: a array of integers
         * @return : return an integer
         */
        public int removeDuplicates(int[] nums) {
            if (nums.length == 0 || nums == null) {
                return 0;
            }
            int count = 1;
            int size = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] == nums[size]) {
                    if (count < 2) {
                        nums[++size] = nums[i];
                        count++;
                    }
                }
                else {
                    nums[++size] = nums[i];
                    count = 1;//
                }
            }
            
            return size + 1;
        }
    }
    View Code
  • 相关阅读:
    ES6数组的扩展--Array.from()和Array.of()
    前端面试中的各种方法实现
    理解 JavaScript call()/apply()/bind()
    【前端面试】变量和类型计算
    Kubernetes1.3新特性:支持GPU
    撸了一个微信小程序项目
    微信开发(调用各种接口)
    Android 神兵利器之通过解析网页获取到的API数据合集,可拿来就用
    Kubernetes1.4正式发布
    Kubernetes1.4即将发布
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8228469.html
Copyright © 2020-2023  润新知