LeetCode-26-已排序数组去重

问题描述

LeetCode - Remove Duplicates from Sorted Array

对已经排好序的数组,去除其中重复的元素,并返回去重后的长度。如[1,2,2,3,3],去重后为[1,2,3] ,去重后长度为3

算法1

两个指针,前者(p)记录当前去重后的最后一个元素,后者(i)不断遍历数组,寻找新元素。

int removeDuplicates(int* nums, int numsSize){
    if(numsSize == 0) return 0;

    int p = 0; // 指向当前去重后数组的最后一个元素,初始为0位置

    for(int i = 1; i < numsSize; i++){
        // 发现新的元素,放到p+1位置
        if( nums[i] != nums[p]) {
            p ++;
            nums[p] = nums[i];
        }
    }

    return p + 1;
}

算法2

来自 Discuss区

遍历数组,使用count记录当前出现了多少次重复
如果出现重复,则count++
如果没有重复,则把当前的元素 i 放到它在去重后数组的位置 i-count处

int count = 0;
for(int i = 1; i < n; i++){
    if(A[i] == A[i-1]) count++;
    else A[i-count] = A[i];
}
return n-count;

Related: pressure washer adapters, things to do in stockbridge, ma in winter, hawaiian bros honolulu chicken recipe, primo hoagies sizes, frantz manufacturing garage door parts, unit 73 rockyview hospital, goat frais de douane, bridge to nowhere death, steven robertson charlotte robertson, antler king honey hole planting dates, contraire de pur, rabbit hole vs armadillo hole, el paso police department mugshots, celebrities buried at pacific view memorial park, sage green and terracotta,Related: little nicky adrian costume, galvanic corrosion between ductile iron and carbon steel, matthew pohlkamp biography, sally fraser church times, levy county mugshots, why did the host of inside the world's toughest prisons change, 2006 ram 1500 fuel pump connector, mistborn spook quotes, greeneville greene devils football schedule, ishrath velshi, what's squidward's phone number, bishop gorman high school famous alumni, picture of bill boulware, ascension flu twin flame, haunted houses in louisville, ky,Related: laghi di avigliana spiaggia, the twelve why did frie kill brechtje, why are recreational sports important, baader meinhof phenomenon covid 19, national park missing persons conspiracy, can a borderline destroy a narcissist, silent auction donation request form, sara allen and daryl hall back together, new york beer project nutrition facts, medical associates east campus lab hours, fred c dames joliet il obituaries, cities on the north carolina virginia border, sherry cohen hackett obituaries, montgomery county conservative voter guide, bird 74km alaskan timberline trail,Related: is christopher the makeover guy married, city of susanville gas and water, 2x28, how to join aternos server on xbox, morrisons swan valley, northampton jobs, madison heights police reports, paul arcand conjointe annick mongeau, said aouita fortune, was gemma whelan in coronation street, glenne headly stirling mcculloch, what happened to elsa garcia tejano singer, where does linda thompson live, michael goulet son of robert goulet, oatmeal survival bars, federal legalization bill 2022 vote date,Related: how old is red skelton's daughter, celebrity birthdays today uk, if i were a scientist, i would invent, 1 tonne de ciment fait combien de brique, sellindge converter station, primos hunting staff, smione child support card, power automate get file properties from url, what does ash mean on tiktok, georgia high school coaches clinic, skylark dwarf fruitless olive tree, did danielle and cody consummate the marriage, yynot rush tribute band, coyote adaptations in the desert, fallout 4 looksmenu presets not looking right,Related: grand pasha hotel & casino, 4 inch pellet stove pipe 45 degree, bleu de chanel travel size, aquarium plant holder 3d print, telegram number of users in a group, truist mortgage address, mobile internet in france, water conductivity meter, health care website ideas, where to stay in barcelona for a month, reebok classic malaysia, tektelic packet forwarder, roland integra 7 synthesizer module, amish built modular homes, lady nail pumpkin seeds nutrition,Related: bridgend recycling centre opening times, hmh into literature grade 10 answer key pdf, brats and sauerkraut in oven, the unification of germany worksheet answer key, louisiana dixie youth baseball 2021, casas alquiler urb aponte, cayey, jennifer aniston friends salad recipe, angulos consecutivos no adyacentes+ejemplos, does vinegar dissolve toilet paper, dublin, ohio shooting, brentwood country club membership los angeles, dazn boxing schedule 2022, can 2 brown eyes make blue eyed baby, best places to find hag stones, cricut gable box template,

作者:JarvisChu
原文链接:LeetCode-26-已排序数组去重
版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

发表评论