zoukankan      html  css  js  c++  java
  • code第一部分:数组

    code第一部分:数组

    都说写代码一定要自己尝试,看再多也没有,确实是的;之前写过很多,感觉可以分享给大家的就放到博客上,希望激励自己好好敲代码。共勉吧!

    之前一段时间把关于数组部分的内容做了一些;每周我会集中上传一次;任务量还是很大的;废话不多说,开始!

    首先我把题目按照大的分类,总结起来了,这一部分是数组部分,思维导图如下

    第一题 从有序数组中移除重复的数据。

    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].

    分析:
    注意是不能分配额外的空间;
    如果没有这个条件,有很多的办法,重新分配一个数组,没重复的数据直接存储;
    但是不能分配,就可以直接使用数组的空间实现;

    解决方法1 :在数组中留一个索引,索引和下标都往后移,重复就不保存,不重复就保存;


    解决办法2 : 如果对STL很熟悉,就可以直接调用STL做;在#include <algorithm>下,
    先调用uniuqe(a,a+n)函数去重,再调用distance来得到去重后数组的大小;


    解决办法3:还是要使用stl中的unique函数,但是如果不知道用distance函数,直接使用
    sizeof(a)/sizeof(int)得到去重后数组的大小

    源代码如下

    #include <iostream>
    
    #include <algorithm>
    
    using namespace std;
    
    int removeduplicate(int a[],int n)
    {
        int i=1;
        int index=0;
        if (n==0)
        {
            cout<<"the length of array is zero"<<endl;
        }
        a[index]=a[0];
        while(i<n)
        {
            if (a[index]!=a[i])
            {
                a[index]=a[i];
                index++;
                i++;
            }
            else
                i++;
        }
        return index+1;
    }
    
    int removeduplicate2(int a[],int n)
    {
        return distance(a, unique(a, a + n));
    }
    
    int removeduplicate3(int a[],int n)
    {
        unique(a, a + n);
        int length=sizeof(a)/sizeof(int);
        return length;
    }
    
    
    int main()
    {
        int a[3]={1,1,2};
        int ans=removeduplicate(a,3);
        cout<<ans<<endl;
        int b[3]={1,1,2};
        int ans1=removeduplicate2(b,3);
        cout<<ans1<<endl;
        int c[3]={1,1,2};
        int ans2=removeduplicate2(c,3);
        cout<<ans2<<endl;
        return 0;
    }

    代码测试通过!

  • 相关阅读:
    How a webpage is loaded and displayed
    Tree知识总结
    Install Cassandra Locally
    axios接口封装
    Jsonp解决跨域问题
    react使用swiper,解决添加点击事件首位图片点击失效,解决轮播按钮被覆盖问题
    vue 生产环境和测试环境的配置
    vue使用远程在线更新代码
    vue.js axios实现跨域http请求接口
    leetcode每日一题(2020-05-27):974. 和可被 K 整除的子数组
  • 原文地址:https://www.cnblogs.com/tao-alex/p/6442969.html
Copyright © 2011-2022 走看看