zoukankan      html  css  js  c++  java
  • [array] leetCode-26. Remove Duplicates from Sorted Array

    26. Remove Duplicates from Sorted Array - Easy

    descrition

    Given a sorted array, remove the duplicates in-place such that each element appear only once 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

    Given nums = [1,1,2],
    
    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
    It doesn't matter what you leave beyond the new length.
    

    解析

    注意题目的要求,in_place,即原址,不能借助额外的辅助空间。
    再关注到另一个有利的前提条件,数组是有序的,因此重复的数字一定挨着,这是达到最优解的关键,时间复杂度 O(n)。

    code

    
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class Solution{
    public:
    	int removeDuplicates(vector<int>& nums){
    		if(nums.empty()) // don't forget the special case!!!!
    			return 0;
    
    		int cur = 0; // the end of new nums
    		for(int i=1; i<nums.size(); i++){
    			if(nums[i] != nums[cur]){
    				nums[++cur] = nums[i];
    			}
    		}
    
    		return cur+1; // return the new length
    	}
    };
    
    int main()
    {
    	return 0;
    }
    
    
  • 相关阅读:
    Session cookie 原理
    asp.net core service mesh
    js 常用库
    asp.net core consul
    asp.net core polly
    asp.net core ocelot
    第十五章 享元模式 Flyweight
    第十四章 策略模式 Strategy
    mysql 主从复制
    mysql 执行计划
  • 原文地址:https://www.cnblogs.com/fanling999/p/7828895.html
Copyright © 2011-2022 走看看