80. Remove Duplicates from Sorted Array II

复制代码
package LeetCode_80

/**
 * 80. Remove Duplicates from Sorted Array II
 * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
 *
 * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.
 * */
class Solution {
    /*
    solution: for loop to check i and each two number, Time complexity:O(n), Space complexity:O(1)
    * */
    fun removeDuplicates(nums: IntArray): Int {
        var index = 0
        for (num in nums) {
            //if current num large than prev two numbers, mean current number is new one after two duplicates
            if (index < 2 || num > nums[index - 2]){
                nums[index++] = num
            }
        }
        return index
    }
}
复制代码

 

posted @   johnny_zhao  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-09-19 3. Longest Substring Without Repeating Characters
点击右上角即可分享
微信分享提示