LeetCode(2) Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

  • 题目 考察数组
    描述
    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 in place with constant memory.
    For example, Given input array A = [1,1,2],
    Your function should return length = 2, and A is now [1,2].

  • C++代码如下
    时间复杂度o(n),空间复杂度o(1):

/*
* Remove Duplicates from Sorted Array
* For example Given input array A= [1,1,2] 
* Your function should return length = 2; and A is now [1,2]
*/

#include <iostream>
using namespace std;


class Solution{


public:
    //返回值,函数参数,实现功能
    //指向整形数组的指针,数组和数组个数,实现对数组元素去重
    int * RemoveDuplicates(int *a,int num){

        //思路:按照判断相邻两个元素是否相同,若不相同,后一个元素覆盖前一个元素
        //      同时index 记录新的数组的个数
        int index =0;

        // 从第二个元素开始比较
        for(int i=1;i<num;i++){
            //如果相邻的两个元素不同
            if(a[index]!=a[i]){
                index++;
                a[index]=a[i];
            }

        }

        for(int j=0;j<=index;j++){
            cout<<a[j]<<" ";
        }
        cout<<endl;


        return a;
    }


};


int main(){

    int a[]={1,1,2,2,3};

    Solution s1;
    s1.RemoveDuplicates(a,5);


    getchar();
    getchar();
    return 0;
}
  • Result
1 2 3

概念理解

const 定义理解

  • const 修饰
    关于const修饰指针的情况,一般分为如下四种情况:
int b =500;
const int* a = &b; //情况1
int const *a = &b;//情况2
int * const a=&b; //情况3
const int* const a= &b; //情况4

如何区别呢?
(1)情况1
如果const 位于星号的左侧,则const就是用来修饰指针所指向的变量的,即指针指向为常量。如果const位于星号右侧,const就是修饰指针本身,即指针本身是常量。因此,情况1和情况2相同,都是指针所指向的内容为常量(const放在变量声明符的位置无关),这种情况下不允许对内容进行更改操作。

举一个通俗的例子,如果a是一名仓库管理员的话,他所进入的仓库,里面的货物(*a)是他没有权限允许动的。

const 与#define相比有什么不同?

  • 解答

  • c++语言可以用const定义常量,也可以用#define定义常量,但是前者比后者有更多的优点:

1、const 常量有数据类型,而宏常量没有数据类型。编译器可以对前者进行类型安全检查,而后者只进行字符替换,没有类型安全检查,并且在字符串替换过程中可能会产生意想不到的错误,也就是边际效应。

2、在有些集成化的调试工具可以对const常量进行调试,但是不能对宏常量进行调试。在c++程序中只是用const常量而不使用宏常量,即const常量完全取代宏定义。

常量的引进是在早期的c++版本中,当时标准C规范正在定制。那时,常量被看做一个好的思想而被包含在C中。但是,C中的const的意思是“一个不能被改变的普通变量”。在C中,它总是占用内存,而且它的名字是全局符。C编译器不能把const看出一个编译期间的常量。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值